Search code examples
c#.netwinformsevent-handlingformclosing

How to set focus to a Control on the Form when cancelling FormClosing event?


I am validating input on textboxes on the FormClosing event of my Form and if the user decides to cancel closing, I set e.Cancel = true so as to stop the FormClosing event. I then try to set focus to the first textbox but this is not working.

private void AddDriver_Window_FormClosing(object sender, FormClosingEventArgs e)
{
    if (this._Cancel(sender, e))
    {
        e.Cancel = true;
        this.textboxFirstName.Focus();
    }
}

If you are interested in seeing the ._Cancel method I asked an unrelated question earlier.


Solution

  • I tried this one Check this is it work for you..

    private void AddDriver_Window_FormClosing(object sender, FormClosingEventArgs e)
    {
        if( DialogResult.Cancel == MessageBox.Show("Do you want to exit programm","Alert",MessageBoxButtons.OKCancel))
        {
            e.Cancel = true;
            textBox1.Focus();
        }
    }
    

    this will popup a message box and if click cancel then automatically focus on the textbox1.