C # button of form X pressed

How can I find out if a form is closed by pressing the X or (this.Close ()) button?

+3
source share
4 answers

the form has a FormClosing event with a parameter of type FormClosingEventArgs.

private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
    if ( e.CloseReason == CloseReason.UserClosing )
    {
        if ( MessageBox.Show( this, "Really?", "Closing...",
             MessageBoxButtons.OKCancel, MessageBoxIcon.Question )
            == DialogResult.Cancel ) e.Cancel = true;
    }
}
+18
source

Can you completely remove the "X"?

One of the properties of the form is "ControlBox", just set this value to false

+2
source

null, :

private void Form1_FormClosing( object sender, FormClosingEventArgs e )
{
    if ( e.CloseReason == CloseReason.UserClosing )
    {
        returnfield = null;
        this.close();
    }
}
+1

OnFormClosing FormClosingEventArgs.CloseReason UserClosing "X", form.Close(). :

//override the OnFormClosing event
        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.ApplicationExitCall)// the reason that you need
                base.OnFormClosing(e);
            else e.Cancel = true; // cancel if the close reason is not the expected one
        }
//create a new method that allows to handle the close reasons
        public void closeForm(FormClosingEventArgs e)
        {
            if (e.CloseReason == CloseReason.UserClosing) this.Close();
            else e.Cancel = true;
        }

  //if you want to close the form or deny the X button action invoke closeForm method
    myForm.closeForm(new FormClosingEventArgs(CloseReason.ApplicationExitCall, false));
                              //the reason that you want ↑

(X)

0

Source: https://habr.com/ru/post/1765294/


All Articles