Kate Kate - 3 months ago 9
C# Question

How to pause processing code till the form hides in C#?

I am new to C# and I am using windows forms.

I have

form1
and
form2
, I show and hide
form2
from
form1
as following:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}


Form2 frm2 = new Form2();
private void button_showForm2_Click(object sender, EventArgs e)
{


frm2.Show();

//I want to show the following message once form2 hides:

MessageBox.Show("Form2 is hidden. Continue processing next line of code");

}
}


In form2:

private void button_HideForm2_Click(object sender, EventArgs e)
{

Hide();

}


When I run the above code and show
form2
,
form2
shows up with the
messageBox
at same time. I know it is because when using
Show()
method it does not hold the program flow and continue executing next lines of code while using
ShowDialog()
holds the program flow till you close the child form.

What I want to do is ( I do not want to use
ShowDialog()
) : I want to show
form2
and when you finish using it and hide it I want to display the above message (in
form1
) when
form2
hides.

Anyone knows how can I do that? Thank you alot.

Answer

Hook the Form's VisibleChanged Event, your code will then get fired when the Forms visibility changes.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    Form2 frm2 = new Form2();
    private void button_showForm2_Click(object sender, EventArgs e)
    {
        frm2.VisibleChanged += new EventHandler(this.FormVisibilityChanged);
        frm2.Show();
    }

    private void FormVisibilityChanged(object sender, EventArgs e)
    {
       frm2.VisibleChanged -= new EventHandler(this.FormVisibilityChanged);
       MessageBox.Show("Form2 is hidden. Continue processing next line of code");
    }
}
Comments