FormClosing and FormClosed events do not work

Both events should work fine. Just open a new project and do this simple test:

 private void Form1_Load(object sender, EventArgs e)
 {
     this.FormClosing += new FormClosingEventHandler(Inicio_FormClosing_1);
     this.FormClosed += new FormClosedEventHandler(Inicio_FormClosed_1);
 }

 private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
 {
     //Things while closing

 }

 private void Inicio_FormClosed_1(object sender, FormClosedEventArgs e)
 {
     //Things when closed
 }

If you set break points in these methods, you would see that they are reached after the close button is clicked. It seems that there is some problem in your event-attaching code. For example: Inicio_FormClosed_1(object sender, FormClosingEventArgs e) is wrong, as far as it should take a FormClosedEventArgs argument; and thus this method is surely not associated with the FormClosed event (otherwise, the code wouldn't compile).


I found the mistake;

Here: (when I initialize my form)

    public Inicio()
    {
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoScroll = true;

        this.ClientSize = new System.Drawing.Size(635, 332);
        this.StartPosition = FormStartPosition.CenterScreen;
        llenaForm(nombreFormulario);
        Application.EnableVisualStyles();

    }

All i needed was: InitializeComponent();
I deleted by mistake

It should be:

    public Inicio()
    {
        this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
        this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
        this.AutoScroll = true;`

        InitializeComponent();//<<<<<<<<------------------- 

        this.ClientSize = new System.Drawing.Size(635, 332);
        this.StartPosition = FormStartPosition.CenterScreen;
        llenaForm(nombreFormulario);
        Application.EnableVisualStyles();
    }

Thank you so much guys!


In order to prevent the user from closing a form in response to certain validations, you need to set FormClosingEventArgs.Cancel = true.

For example:

private void Inicio_FormClosing_1(object sender, FormClosingEventArgs e)
{
    if (string.IsNullOrEmpty(txtSomethingRequired.Text))
    {
        MessageBox.Show("Something is required here!");
        if (txtSomethingRequired.CanFocus) txtSomethingRequired.Focus();
        e.Cancel = true;
        return;
    }
}

You can only do validations in the FormClosing event to prevent the form from closing; if you wait until FormClosed it is already too late.

Tags:

C#

Forms

Events