Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why FormShown event does not get fired in C#?

Tags:

c#

winforms

I am new to C# and I am using windows forms. I have Form1 and Form2. In form1 I use the following code to show form2:

Form2 frm2 = new Form2();
private void button1_Click(object sender, EventArgs e)
{          
    frm2.Show();
}

What I want is: I want to do some activities when Form2 is shown every time. I placed messageBox in the Form2Shown event (for a test) but it only gets fired once and next time I show Form2 it never get fired. I also tried to use formLoad but it only get fired once and next time I show form2 it never get fired. I know I can use frm2.ShowDialog() to fire shown event every time but I do not want for some reasons.

private void Form2_Shown(object sender, EventArgs e)
{
    MessageBox.Show("Form2 is shown"); // this gets fired only once when form2 is shown.
                                       // when I show form2 again it does not get fired.
}

private void button_Hide_Form2_Click(object sender, EventArgs e)
{

    // this is in form2
    Hide();
}

My question is: Anyone knows how to fire an event every time form2 is shown? I am happy to obtain some new ideas to solve this issue. Thank you

like image 680
Kate Avatar asked Dec 11 '22 15:12

Kate


1 Answers

From MSDN

The Shown event is only raised the first time a form is displayed; subsequently minimizing, maximizing, restoring, hiding, showing, or invalidating and repainting will not raise this event.

On MSDN you can see what events are raised. And choose one which meets your requirements.

Some example.

Form1 - two buttons, Show and Hide

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

    Form2 frm = new Form2();

    private void btnShow_Click(object sender, EventArgs e)
    {
        frm.Show();
    }

    private void btnHide_Click(object sender, EventArgs e)
    {
        frm.Hide();
    }
}

Form2 - shows msgbox when shown. I change form close behavior to hide form not destroy.

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

    private void Form2_VisibleChanged(object sender, EventArgs e)
    {
        if(this.Visible == true)
            MessageBox.Show("Hey");
    }

    private void Form2_FormClosing(object sender, FormClosingEventArgs e)
    {
        e.Cancel = true;
        this.Hide();           
    }
}
like image 111
BWA Avatar answered Dec 27 '22 01:12

BWA