且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在一个线程中打开窗体,并迫使它继续开放

更新时间:2023-12-06 15:40:10

在一个新的线程,调用Application.Run传递表单对象,这将使线程中运行自己的消息循环,而窗口已打开。

然后就可以调用。加入该线程,使你的主线程等待,直到UI线程已经终止,或者使用类似的技巧,等待该线程完成。

例如:

 公共无效StartUiThread()
{
    使用(Form1中_form =新Form1中())
    {
        Application.Run(_form);
    }
}
 

I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed here.

In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it.

using System;
using System.Windows.Forms;
using System.Threading;

namespace UIThreadMarshalling {
    static class Program {
    	[STAThread]
    	static void Main() {
    		Application.EnableVisualStyles();
    		Application.SetCompatibleTextRenderingDefault(false);
    		var tt = new ThreadTest();
    		ThreadStart ts = new ThreadStart(tt.StartUiThread);
    		Thread t = new Thread(ts);
    		t.Name = "UI Thread";
    		t.Start();
    		Thread.Sleep(new TimeSpan(0, 0, 10));
    	}

    }

    public class ThreadTest {
    	Form _form;
    	public ThreadTest() {
    	}

    	public void StartUiThread() {
    		_form = new Form1();
    		_form.Show();
    	}
    }
}

On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.

Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.

Example:

public void StartUiThread()
{
    using (Form1 _form = new Form1())
    {
        Application.Run(_form);
    }
}