Marcel
Marcel

Reputation: 27

Closing Form with X or created button

I have a Log In form and I need to know if user pressed the X button on form or the button that takes him to the new form. If user closed the program with Alt+F4 or X button the program must be closed.

I was trying with FormClosing event to check whether user pressed X or login.

 private void LogIn_FormClosing(object sender, FormClosingEventArgs e)
    {
        if (string.Equals((sender as Button).Name, @"loginButton"))
        {
            //some code
        }
        else
        {
            Close();
        }
    }

Upvotes: 1

Views: 82

Answers (1)

Steve
Steve

Reputation: 216303

The FormClosing event handler receives a FormClosingEventArgs argument that contains the property CloseReason, but in your context this is not enough.
Indeed, in both cases (ALT+F4/X-Click or ButtonClick) the argument will contain a CloseReason equal to UserClosing.

I suggest you a simple workaround. In your button click handler (where you should call the close action on the form, not on the formclosing event handler itself), add something to the Tag property of the form like so:

private void Button1_Click(object sender, EventArgs e)
{
    this.Tag = "ClosedByUser";
    this.Close();
}

now in the FormClosing event handler is simple to check this property

private void LogIn_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this.Tag != null)
    {
        // Button clicked
    }
    else
    {
        // other reasons
        // Dp not call Close here, you are already closing 
        // if you don't set e.Cancel = true;
    }
}

Upvotes: 1

Related Questions