I have a Windows Forms application that when the Main Window is closing, it displays a basic dialog box, confirming the action. If the user decides to cancel the application
In your FormClosing event check the FormClosingEventArgs' CloseReason property to see why the window is closing down. If it is CloseReason.WindowsShutDown then don't show your dialog and do not cancel the closing of your form.
private void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
// Verify that we're not being closed because windows is shutting down.
if (e.CloseReason != CloseReason.WindowsShutDown)
{
// Show your dialog / cancel closing.
}
}
N.B: You might also want to include CloseReason.TaskManagerClosing as the user clearly wants to close your application in that scenario and the taskmanager already asks for confirmation. Or alternatively only show your dialog for CloseReason.UserClosing.