WinForms form freezes - c#

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

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

Related

Changing text in one form, from another form

Im trying to change the text in Form1 when pushing the button on Form2
Form 2:
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.textCh = "Text has been changed";
}
}
Form 1:
public partial class Form1 : Form
{
public string textCh {
get
{
return this.textCh;
}
set
{
this.label1.Text = value;
}
}
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.ShowDialog();
}
}
When I'm pushing button nothing happens, the text remain the same.
Another method of passing Form1 to Form2 via the Show() method and the .Owner property:
// In Form1
Form2 f2 = new Form2();
f2.ShowDialog(this); // <-- pass Form1 via "this"
Then, in Form2, you CAST .Owner to type Form1:
// In Form2
Form1 f1 = this.Owner as Form1;
if (f1!=null && !f1.IsDisposed)
{
f1.textCh = "Text has been changed";
}
There are several way to do this here 2 examples
This example use references whitout any use of events
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2(this);
frm.Show();
}
}
here the Form2 is created passing the Form1 as parameter
public partial class Form2 : Form
{
Form1 _parent;
public Form2(Form1 parent)
{
_parent = parent;
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var lbl = (Label)_parent.Controls.Find("label1", false).First();
lbl.Text = "new text";
_parent.Update();
}
}
Than the Form2 use that for set the value wanted.
This example use events
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var frm = new Form2();
frm.UpdateLabelEvent += Frm_UpdateLabelEvent;
frm.Show();
}
private void Frm_UpdateLabelEvent(string str)
{
label1.Text = str;
}
}
and here the code of Form2
public partial class Form2 : Form
{
public event Action<string> UpdateLabelEvent;
public Form2()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
UpdateLabelEvent("new string value");
}
}
Nothing changes in your Form1 because you are creating a new Form1 first and change the text there. The new Form1 is never shown, so you see no changes.
Solution
private void button1_Click(object sender, EventArgs e)
{
//Form1 f1 = new Form1(); GET rid of this line
f1.textCh = "Text has been changed";
}
you need to make sure off course that f1 is known in form2, if you dont know how here is a simple way to do that
private void button1_Click(object sender, EventArgs e)
{
Form2 f2 = new Form2();
f2.f1 = this;
f2.ShowDialog();
}
public Form2()
{
public Form1 f1 { get; set; }
...

Change the form.text programmatically with a button of other form

I can't update the first form of my application. when it opens it loads all the elements, then through a button I open a second form and from that, with a button I should reload all the controls of the first form including form1.text but this does not happen. despite the marker I saw that the text variable is updated correctly, however on a graphic level it does not change.
form1:
public partial class Form1 : Form
{
public string mail { get; private set; }
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
this.Text = "table - Last Update: " + DateTime.Now.ToString();
...some other code...
}
public void updateform()
{
this.Controls.Clear();
InitializeComponent();
Form1_Load(null, null);
this.Refresh();
}
private void button1_Click(object sender, EventArgs e)
{
mail = lbl1.Text;
Form2 form2 = new Form2(mail);
form2.Show();
}
}
form2:
public partial class Form2 : Form
{
public Form2(String stringa)
{
InitializeComponent();
email = stringa;
}
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = new Form1();
f1.updateform();
this.Close();
}
You can pass a reference to Form1, into Form2 using the Show() command. The reference can be accessed using the .Owner property.
In Form1:
private void button1_Click(object sender, EventArgs e)
{
mail = lbl1.Text;
Form2 form2 = new Form2(mail);
form2.Show(this); // <-- pass reference to Form1
}
In Form2:
private void button1_Click(object sender, EventArgs e)
{
Form1 f1 = this.Owner as Form1; // <-- attempt to convert .Owner to Form1
if (f1 != null)
{
f1.updateform();
}
this.Close();
}

How to get string data in main form from second from, when button on second form is clicked in C# .net?

At first I thought that it won't be a problem for me, but now I can't figure it out. So,
when I click Button1 in main form, form2 opens. Form2 is simple numeric keyboard, that user can enter some data. On form2 is also Save. When user clicks it, entered value should pass to main form and from that moment some event must happen in main form, which contains data from form2. Could you please give me some example or any kind of help? Thanks!
// code from main form to create form2
private void button1_Click(object sender, EventArgs e)
{
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
//button save on form2
private void button13_Click(object sender, EventArgs e)
{
this.ReturnValue1 = "Something";
this.ReturnValue2 = DateTime.Now.ToString(); //example
this.Close();
//after this, some event should happen in main form !
}
There is a lot of solutions to do what you want; but I think one of these will resolve your problem.
1- Simple and easy: use public properties in Form2, initialize them when buttonSave get clicked, and access them in Form1:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
YourDate = "something";
Close();
}
public object YourDate { get; private set; }
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
var f2 = new Form2();
f2.ShowDialog();
var data = f2.YourDate;
}
}
2- A better way, is using events which is more flexible and professional programming friendly:
Form2:
public partial class Form2 : Form {
public Form2() {
InitializeComponent();
}
// create an event of Action<T> which T is your data-type. e.g. in this example I use an object.
public event Action<object> SaveClicked;
// create an event invocator, to invoke event whenever you want
protected virtual void OnSaveClicked(object data){
var handler = SaveClicked;
if (handler != null)
handler(data);
}
private void button1_Click(object sender, EventArgs e){
// prepare your data here, -object, or string, or int, or whatever it is
var data = PrepareYourDataHere;
// invoke the event
OnSaveClicked(data);
Close();
}
}
Form1:
public partial class Form1 : Form {
public Form1() {
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e){
// create an instance of Form2
var f2 = new Form2();
// add an event listener to SaveClicked event -which we have declared it in Form2
f2.SaveClicked += f2_SaveClicked;
f2.Show();
// or: f2.ShowDialog();
}
void f2_SaveClicked(object obj) {
// get data and use it here...
// any data which you pass in Form2.OnSaveClicked method, will be accessible here
}
}
UPDATE:
If you want to fire some events in form1, just after form2 closed, you can simply add a listener to Form2.FormClosed event:
// code from main form to create form2
private void button1_Click(object sender, EventArgs e) {
// Create a new instance of the Form2 class
Form2 settingsForm = new Form2();
settingsForm.FormClosed += SettingFormClosed;
// Show the settings form
settingsForm.Show();
string val = settingsForm.ReturnValue1;
MessageBox.Show(val);
}
void SettingFormClosed(object sender, FormClosedEventArgs e) {
// this method will be called automatically when form2 closed
}
here a sample how you can achieve this
//here I suppose that form1 is the mainform
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void UpdateMainForm(string updatedString)
{
//here you can update and invoke methods
//Once called you could raise events in your mainform
}
private void button1_Click(object sender, EventArgs e)
{
using (Form2 form2 = new Form2(this))
{
form2.ShowDialog();
}
}
}
Form2
public partial class Form2 : Form
{
private Form1 _mainForm1;
public Form2(Form1 mainForm1)
{
InitializeComponent();
_mainForm1 = mainForm1;
}
private void button1_Click(object sender, EventArgs e)
{
_mainForm1.UpdateMainForm( DateTime.Now.ToString());
}
}

if called window is already running then close it and run newly called window

In my app in several time i have to call a window(class). the work of this window is to show the meaning of a word.when i again call that window a new window shows but the previous one also shows.
I have two form named form1,form2.
Form1 is like that:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
Form2 s = new Form2(a);// it will be called as many time as i click
s.Show();
}
}
Form2 is like that:
public partial class Form2 : Form
{
public Form2(string s)
{
InitializeComponent();
label1.Text = s;
}
}
what i want is that inside form1 if i call form2 it shows but if i call form2 again the previous form2 window will be closed automatically and new form2 window will be shown instead of previous one.
How can i do that????
Here's an example of storing the Form2 reference at class level, as mentioned by the others already:
public partial class Form1 : Form
{
private Form2 f2 = null;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (f2 != null && !f2.IsDisposed)
{
f2.Dispose();
}
string a = textBox1.Text;
f2 = new Form2(a);
f2.Show();
}
}
I think you should consider using singleton pattern.
You can implement it like this:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string a = textBox1.Text;
Form2.ShowMeaning(a);// it will be called as many time as you click
}
}
and Form2
public partial class Form2 : Form
{
private static readonly Form2 _formInstance = new Form2();
private Form2()
{
InitializeComponent();
}
private void LoadMeaning(string s)
{
label1.Text = s;
}
//Override method to prevent disposing the form when closing.
protected override void OnClosing(CancelEventArgs e)
{
e.Cancel = true;
this.Hide();
}
public static void ShowMeaning(string s)
{
_formInstance.LoadMeaning(s);
_formInstance.Show();
}
}
Hope it helps.

How to properly listen form events with another form

Stuck in listening event to another form.
When I try to close my Form2, nothing happens on Form1. I want to do something in Form1 when Form2 closes.
Here is my code for Form1
public partial class Form1: Form
{
public Form1()
{
InitializeComponent();
Form2 frm2= new Form2();
frm2.FormClosing += new FormClosingEventHandler(frm2_FormClosing);
}
void frm2_FormClosing(object sender, FormClosingEventArgs e)
{
throw new NotImplementedException();
}
You will need to show the object which you are implementing it's FormClosing event. Since the new object you are creating is in your constructor I assume that frm2 isn't the Form which you are showing, which means you are not handling the event.
public Form1()
{
InitializeComponent();
Form2 frm2 = new Form2();
frm2.FormClosing += frm2_FormClosing;
frm2.Show();
}
void frm2_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Form2 is closing");
}
you create a new instance of form2, and listen to its closing event - but from your posted code you don't ever show it? Not sure what I'm missing but what you think should work does work - i.e :
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Form2 frm2 = new Form2();
frm2.FormClosing += frm2_FormClosing;
frm2.Show();
}
void frm2_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("form 2 closed");
}
}

Categories