Create a Windows Form from a background Thread

戏子无情 提交于 2021-02-07 09:31:44

问题


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

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.

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.

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?


回答1:


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

Where GuiContext is the stored instance of the SynContext.




回答2:


Another way to do this without any global variables is (sorry for VB.NET - was doing this in VB.NET):

 Dim result as Object
 Dim deleg As ThreadStart = Sub() result = DoSomethingHere()
 If Thread.CurrentThread.GetApartmentState <> ApartmentState.STA Then
 Dim t As New Thread(deleg)
     t.SetApartmentState(ApartmentState.STA) 'Set the thread to STA
     t.Start()
     t.Join() 'Wait for the thread to end
 Else
     deleg.Invoke()
 End If


来源:https://stackoverflow.com/questions/6109159/create-a-windows-form-from-a-background-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!