2014-12-31 19 views
0

我有一个FormClosing方法让我的程序询问用户他是否想在关闭表单之前退出程序。这很好,但我不希望当程序由于系统关闭/注销而关闭时出现对话框。如何检测kill命令是否由系统发送,而不是由用户单击我的表单的x? Envrionment.HasShutdownStarted不起作用。C#如何检测杀死事件发件人

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(); 
    } 
} 
+0

参见:http://stackoverflow.com/questions/6799955/how-to-detect-windows-shutdown-or-logoff – NoChance

回答

2

尝试检查e.CloseReason,例如,

private void Form1_FormClosing(object sender, FormClosingEventArgs e) 
{ 
    if (e.CloseReason != CloseReason.WindowsShutDown) 
    { 
     if (MessageBox.Show(...) == DialogResult.No) 
     { 
      e.Cancel = true; 
      this.Activate(); 
     } 
    } 
} 
+0

谢谢你,这个工作! –