开发者

WinForms form freezes

On a form (F1) i have a button, from which if i create another form (lets call it F2) and show it there's no problem

but i'd like to do something like this

Some thread in my app is running a connection and listens for messages from a server. when a message arrives, my main form is registered to get an event that runs a function. From that function i'm trying to create and show the F2 type form (empty, nothing modified in it): it shows it but then it freezes my application.

more exactly:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ConnectionManagerThread.getResponseListener().MessageReceived += Form1_OnMessageReceived;
    }

    private void Form1_OnMessageReceived(object sender, MessageEventArgs e) {
     开发者_StackOverflow   Form2 f2 = new Form2();
        f2.Show();
    }
}


I think the reason is you are performing cross thread operations. You need to put the creation of the form on the UI thread before creating form2. I think following will help you

  public delegate void ShowForm(object sender, MessageEventArgs e);
  public partial class Form1 : Form
  {
     public Form1()
     {
        InitializeComponent();
        ConnectionManagerThread.getResponseListener().MessageReceived += Form1_OnMessageReceived;
     }

     private void Form1_OnMessageReceived(object sender, MessageEventArgs e)
     {
         if (this.InvokeRequired)
         {
            this.BeginInvoke(new ShowForm((Form1_OnMessageReceived), new object[] { sender, e }));
         }
         else
         {
            Form2 f2 = new Form2();
            f2.Show();
         }
      }
  }


using Ram's code i finally got to this and it works

thanx!

public delegate void ShowForm(object sender, MessageEventArgs e);

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        ConnectionManagerThread.getResponseListener().MessageReceived += Form1_OnMessageReceived;
    }

     private void Form1_OnMessageReceived(object sender, MessageEventArgs e)
     {
         ShowForm2(sender, e);
     }

    private void ShowForm2(object sender, MessageEventArgs e)
    {
        if (this.InvokeRequired)
        {
            ShowForm f = new ShowForm(ShowForm2);
            this.Invoke(f, new object[] { sender, e });
        }
        else
        {
            Form2 f2 = new Form2();
            f2.Show();
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜