Search code examples
c#winformsvalidationclickformclosing

Validating Close method and Windows Close button C#


I am having a method like MainPage_FormClosing(object sender, FormClosingEventArgs e) and I am using Close method to close the form. This this.Close() method also triggers the MainPage_FormClosing method.

I just want to perform some function specifically when the user click on Form Windows Close Button.

I have seen some other questions here, they used some way like String.Equals((sender as Button).Name, @"CloseButton") to validate. The sender is always null for me

How can I validate this ?


Solution

  • If you can't use e.CloseReason, the simplest solution would be to use a flag - Have a form level boolean variable that will only change it's state if you are closing the form in code and in the form closing event handler. Something like this will do:

    private bool _isClosedFromCode = false;
    

    ...

    private void CloseForm()
    { 
        _isClosedFromCode = true;
        Close();
    }
    

    ...

    private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
    {
        if(_isClosedFromCode)
        {
            // do your stuff here
        }
    
       _isClosedFromCode = false; 
    }