2016-08-19 72 views
0

我可以在gtk#app中使用OpenFileDialog for windows吗? 当我在我的应用程序中使用此示例代码时,它冻结并崩溃。 我也使用线程。它是具有OpenFileDialog代码的工作者。使用窗口从gtk

using System; 
using Gtk; 
using System.Threading; 
namespace Test 
{ 
public partial class basec : Gtk.Window 
{ 
    public basec() : 
      base(Gtk.WindowType.Toplevel) 
    { 
     this.Build(); 
    } 
    protected void OnDeleteEvent(object sender, DeleteEventArgs a) 
    { 
     Window win = new Window(); 
     win.Show(); 
     this.Destroy(); 
    } 
    protected virtual void OnButtonAddPClicked(object sender, System.EventArgs e) 
    { 
     brows workerObject = new brows(); 
     Thread workerThread = new Thread(workerObject.DoWork); 
     workerThread.Start(); 
     while (!workerThread.IsAlive); 
     Thread.Sleep(1); 
     workerObject.RequestStop(); 
     workerThread.Join(); 
    } 
    protected virtual void OnButtonMenuClicked(object sender, System.EventArgs e) 
    { 
     Window win = new Window(); 
     win.Show(); 
     this.Destroy(); 
    } 
    protected virtual void Exits(object sender, System.EventArgs e) 
    { 
     Window win = new Window(); 
     win.Show(); 
     this.Destroy(); 
    } 
} 
} 

工人:

using System; 
using System.IO; 
using System.Windows.Forms; 
namespace Test 
{ 
public class brows 
{ 
    // This method will be called when the thread is started. 
    public void DoWork() 
    { 
     Stream myStream = null; 
     OpenFileDialog openFileDialog1 = new OpenFileDialog(); 

     openFileDialog1.InitialDirectory = "c:\\"; 
     openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; 
     openFileDialog1.FilterIndex = 2; 
     openFileDialog1.RestoreDirectory = true; 

     if (openFileDialog1.ShowDialog() == DialogResult.OK) 
     { 
      try 
      { 
       if ((myStream = openFileDialog1.OpenFile()) != null) 
       { 
        using (myStream) 
        { 
         // Insert code to read the stream here. 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message); 
      } 
     } 
    } 
    public void RequestStop() 
    { 
     _shouldStop = true; 
    } 
    private volatile bool _shouldStop; 
} 
} 

销毁窗口是因为我的应用程序中使用多重窗口,这是我的第一个项目GTK。

+0

将您的应用程序转换为MONO ... – MethodMan

+0

您可以显示DoWork()的实现吗?这听起来像是你有一个线程问题,但我看不到你的线程代码。此外,为什么你每次点击按钮都会毁掉自己?或者每个按钮点击一个新窗口? [也GTK + 3.20及以上允许您使用系统原生文件对话框,如果这是你想要的。](https://developer.gnome.org/gtk3/stable/gtk3-GtkFileChooserNative.html)(请注意,它使用IFileDialog ,而不是GetOpenFileName(),但是您应该在需要Vista和更高版本的程序中使用IFileDialog,而GTK + 3.18及更高版本则需要Vista,并且需要开始。) – andlabs

+0

更新代码和更多详细信息。 –

回答

0

将线程设置为STA ApartmentState解决问题。谢谢!

Thread workerThread = new Thread(workerObject.DoWork); 
workerThread.SetApartmentState(ApartmentState.STA); 
workerThread.Start();