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

由网友(旧巷故人)分享简介:我仍然有问题搞清楚如何在我讨论here.在试图弄清楚这一点,我写了下面的简单的测试程序。我只是希望它的命名为UI线程一个单独的线程中打开窗体,并保持只要同时允许用户与表单交互(纺纱是欺骗)的形式是开放运行的线程。我明白了为什么下面的失败和线程立即关闭,但我不知道是我应该做的,以修复它。使用系统;使用System.Wi...

我仍然有问题搞清楚如何在我讨论here.

在试图弄清楚这一点,我写了下面的简单的测试程序。我只是希望它的命名为UI线程一个单独的线程中打开窗体,并保持只要同时允许用户与表单交互(纺纱是欺骗)的形式是开放运行的线程。我明白了为什么下面的失败和线程立即关闭,但我不知道是我应该做的,以修复它。

 使用系统;
使用System.Windows.Forms的;
使用的System.Threading;

命名空间UIThreadMarshalling {
    静态类节目{
    [STAThread]
    静态无效的主要(){
    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(假);
    变种TT =新ThreadTest();
    的ThreadStart TS =新的ThreadStart(tt.StartUiThread);
    线程t =新主题(TS);
    t.Name =UI线程;
    t.Start();
    Thread.sleep代码(新时间跨度(0,0,10));
    }

    }

    公共类ThreadTest {
    形成_form;
    公共ThreadTest(){
    }

    公共无效StartUiThread(){
    _form =新Form1中();
    _form.Show();
    }
    }
}
 

解决方案 VB中单机窗体2按钮重新执行窗体1的程序怎样做

在一个新的线程,调用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);
    }
}

阅读全文

相关推荐

最新文章