在WinForms应用程序中第二次未检测到任务管理器关闭 [英] Task manager close is not detected second time in a WinForms Application

查看:127
本文介绍了在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行,并且不关闭表单.

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.

现在的事情是,在这之后,如果我从任务管理器中关闭了应用程序,则关闭的原因是UserClosing!为什么?不应该是TaskManagerClosing吗?

Now the thing is, after this if i close the application from task manager the close reason is UserClosing !!! Why? Shouldn't it be TaskManagerClosing?

推荐答案

我找到了线程加上我们自己的 nobugz 的答案:

I found a thread with an answer by our very own nobugz:

Windows窗体无法检测到 接近原因来自任务 经理.所以它会自动 将CloseReason.None转换为 CloseReason.TaskManagerClosing. 问题是,一旦您尝试关闭 与"X",设置CloseReason 到UserClosing并且不会重置 如果取消关闭,则返回无. 马虎.

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.

并在其旁边,另一个用户解释如何使用反射(由于它是只读的)将e.CloseReason的值更改为无",以解决此问题(应在设置e.Cancel时应用改为True):

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):

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

fi.SetValue(this, CloseReason.None);

这篇关于在WinForms应用程序中第二次未检测到任务管理器关闭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆