0

I have a FormClosing method for my program to ask the user if he want to exit the program before closing the form. This works great, but I don't want the dialog to show up when the program closes because of a system shutdown / logout. How can I detect that the kill command is sent by the system and not by the user clicking the x of my form? Envrionment.HasShutdownStarted does not work.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Need to check for system shutdown here before the next if is activated
    if (MessageBox.Show(...) == DialogResult.No)
    {
        e.Cancel = true;
        this.Activate();
    }
}
Jan H.
  • 41
  • 8

1 Answers1

2

Try checking e.CloseReason, e.g.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason != CloseReason.WindowsShutDown)
    {
        if (MessageBox.Show(...) == DialogResult.No)
        {
            e.Cancel = true;
            this.Activate();
        }
    }   
}
NeddySpaghetti
  • 13,187
  • 5
  • 32
  • 61