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) {
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();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With