开发者

How to display a form from another thread

I am running this code in a seperate thread on my C# Winforms app (the name of my form is MainForm):

DisplayDownload form2 = new DisplayDownload();

form2.TopMost = true;  
form2.Show();

But when the thread is launched, the form never opens. If I move the code onto the main thread of my app, it opens fine, but if I laun开发者_StackOverflowch it as it's own thread, the form never opens.

I tried using the accepted answer from this post: Calling a windows form from another thread (.Net) but I get this error:

Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

Here is the code I am trying to utilize:

MainForm.Invoke(delegate {
         DisplayDownload form2 = new DisplayDownload();


         form2.TopMost = true; 
         form2.Show();
});

Can someone please tell me what I am doing wrong and how to get it to work?


Add new MethodInvoker(delegate(), So:

MainForm.Invoke(new MethodInvoker(delegate() 
{
             DisplayDownload form2 = new DisplayDownload();


             form2.TopMost = true; 
             form2.Show();
}));


You need to explicitly instantiate a delegate type:

MainForm.Invoke(new Action(delegate { ... }));

C# 2 and later can implicitly convert method groups to delegates, but only to a specific delegate type.
The Invoke method takes the base Delegate class, so there is no specific delegate type for the compiler to create.
Therefore, you need to explicitly create a delegate yourself.


Which thread do you want to handle events for the new Form? If you want the main thread to handle events, then use Control.Invoke as the existing examples suggest.

If you want the new thread to manage its own UI events, then you need to call Application.Run. When you do that, the form will be able to paint itself and will become visible on the screen.


    //This is for WPF Application 
     try
       {
        Application.Current.Dispatcher.Invoke(new Action(() => { 
         DisplayDownload form2 = new DisplayDownload();
         form2.TopMost = true; 
         form2.Show();
        }));
        }
        catch(Exception ex) {
         }

      
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜