c# – 在WinForms应用程序中第二次未检测到任务管理器关闭

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    if (e.CloseReason == CloseReason.UserClosing)
    {
        if (MessageBox.Show(this, "Do you really want to close?", "Close?", 
                            MessageBoxButtons.YesNo) == DialogResult.No)
        {
            e.Cancel = true;
        }
    }
}

因此,当我想关闭应用程序时,单击关闭按钮,消息框将显示为应该,然后我选择否.然后执行e.Cancel = true行并且不关闭表单.

现在问题是,在此之后,如果我从任务管理器关闭应用程序,关闭原因是UserClosing !!!为什么?不应该是TaskManagerClosing吗?

最佳答案 我找到了
thread,我们自己的
nobugz得到了答案:

Windows Forms cannot detect that the
close reason came from the Task
Manager. So it automatically
translates CloseReason.None to
CloseReason.TaskManagerClosing.
Problem is, once you tried to close
with the “X”, the CloseReason is set
to UserClosing and doesn’t get reset
back to None if you cancel the close.
Sloppy.

接下来,另一个用户解释如何使用Reflection将e.CloseReason的值更改为None(因为它是只读的),以解决此问题(这应该在将e.Cancel设置为True时应用) :

FieldInfo fi = typeof(Form).GetField("closeReason", BindingFlags.Instance | BindingFlags.NonPublic);

fi.SetValue(this, CloseReason.None);
点赞