2016-08-19 62 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();