Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Form.closed event is not firing

Whenever I click on form's red cross close button I want to display another form, but despite of having closed event handler, I'm unable to open another form.

This is how I'm trying to open another form:

private void Form1_Closed(object sender, System.EventArgs e)
{
     itemMaster.Show();

}

Could anyone please tell me how can I enable my requirment?

like image 868
Jackson Avatar asked Oct 30 '25 02:10

Jackson


2 Answers

First, you should use the FormClosed event instead of Closed:

The Closed event is obsolete in the .NET Framework version 2.0; use the FormClosed event instead. — MSDN page for the Form.Closed event

void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
    // ...
}

Second, make sure that you have actually subscribed to Form1's FormClosed event:

Form1.FormClosed += Form1_FormClosed;

The Windows Forms designer should've automatically added a similar line somewhere in InitializeComponent. If not, that's why your handler method doesn't get called.

If this still doesn't help, try handling the FormClosing event insteaf of FormClosed.

like image 123
stakx - no longer contributing Avatar answered Nov 01 '25 18:11

stakx - no longer contributing


If you have started your application with the following statement:

Application.Run(new Form1());

When you close Form1, your application will exit. Even if you open another form, it will be killed when application quits. Can you make sure this is the case by putting a breakpoint in your Form1_Closed method and see that the breakpoint is hit?

If this is the case, what happens is your code does execute but since the application quits, your another form also closes as soon as it opens.

To fix that, Hide() form1 instead of closing it. Handle Form_Closing event and call this.Hide() and set e.Cancel = true.

like image 29
decyclone Avatar answered Nov 01 '25 17:11

decyclone



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!