从后台线程创建 Windows 窗体 [英] Create a Windows Form from a background Thread

查看:55
本文介绍了从后台线程创建 Windows 窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个 VS 包,但遇到了这个问题:

I'm developing a VS Package and I have this problem:

我有一个后台线程,它每隔几秒钟检查一次必须完成的特定更改.这包括更改 VS 2010 的 GUI,由于某种原因,它可以完美运行无需调用.

I have a Background-Thread which checks every few seconds for specific changes that have to be done. This includes changing the GUI of VS 2010, which works perfectly fine without an invoke for some reason.

无论如何,如果我尝试打开一个新表单,它会打开,但没有显示任何内容,有点崩溃并且没有响应.
我已经尝试过 Application.OpenForms[0].invoke(/* delegate to create the form */).
这很好用,但我没有一直打开表单.
我还尝试创建一个 System.Windows.Forms.Timer,但它首先没有启动.

Anyway if I try to open a new Form, it opens, but it doesn't show anything, kind of crashes and doesn't respond.
I've already tried Application.OpenForms[0].invoke( /* delegate to create the form */).
This works fine, but I don't have an open form all the time.
I've also tried to create a System.Windows.Forms.Timer, but it doesn't start in the first place.

问题:如何获得正确的 GUI 线程来调用我的表单?
或者更确切地说:如何从我的后台线程创建一个新表单?

Question: How can I get the correct GUI thread to invoke my Form?
or rather: How can I create a new Form from my background thread?

推荐答案

在主应用程序启动时将 SynchronizationContext.Current 的实例存储在某处.一旦设置.您可以在任何其他线程中尝试以下代码.

Store instance of SynchronizationContext.Current somewhere when your main application starts. Once set up. you can try following code in any other thread.

 GuiContext.Send(_ => {
                        Form2 frm2=new Form2();
                        frm2.ShowDialog();
                       }, null);

其中 GuiContext 是 SynContext 的存储实例.

Where GuiContext is the stored instance of the SynContext.

这篇关于从后台线程创建 Windows 窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆