简体   繁体   English

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

[英]Task manager close is not detected second time in a WinForms Application

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;
        }
    }
}

So when I want to close the application clicking the close button the message box is shown as it should, then I chose no. 因此,当我要关闭应用程序时,单击关闭按钮,将显示消息框,然后选择否。 Then the line e.Cancel = true is executed and the form is not closed. 然后执行e.Cancel = true行,并且不关闭表单。

Now the thing is, after this if i close the application from task manager the close reason is UserClosing !!! 现在的事情是,在这之后,如果我从任务管理器关闭了应用程序,则关闭的原因是UserClosing! Why? 为什么? Shouldn't it be TaskManagerClosing? 不应该是TaskManagerClosing吗?

I found a thread with an answer by our very own nobugz : 我通过我们自己的nobugz找到了一个带有答案的线程

Windows Forms cannot detect that the close reason came from the Task Manager. Windows窗体无法检测到关闭原因来自任务管理器。 So it automatically translates CloseReason.None to CloseReason.TaskManagerClosing. 因此,它将自动将CloseReason.None转换为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. 问题是,一旦尝试使用“ X”关闭,CloseReason设置为UserClosing,并且如果您取消关闭,则不会重置为“无”。 Sloppy. lop

And next to it, an explanation by another user on how to change e.CloseReason's value to None using Reflection (since it is read-only), to work-around this problem (this should be applied when setting e.Cancel to True): 紧接着,另一位用户对如何使用反射将e.CloseReason的值更改为“无”(因为它是只读的)进行了说明,以解决此问题(将e.Cancel设置为True时应使用此方法) :

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

fi.SetValue(this, CloseReason.None);

请参阅使用CloseReason.TaskManagerClosing捕获该问题的答案

Just the translation of you code in VB: 只是您在VB中的代码翻译:

Imports System.Reflection
Private Sub ResetCloseReason()
  Dim myFieldInfo As FieldInfo
  Dim myType As Type = GetType(Form)
  myFieldInfo = myType.GetField("closeReason", BindingFlags.NonPublic Or _
                    BindingFlags.Instance Or BindingFlags.Public)
  myFieldInfo.SetValue(Me, CloseReason.None)

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM