使用 windows 来自 gtk

Use windows froms with gtk

我可以在 windows 的 gtk# 应用程序中使用 OpenFileDialog 吗? 当我在我的应用程序中使用此示例代码时,它会冻结并崩溃。 我也使用线程。它是 OpenFileDialog 代码的工作人员。

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;
}
}

销毁 windows 是因为我的应用程序使用 multiply window 并且这是我的第一个 gtk 项目。

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

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