C# Windows 应用程序阻止 Windows 关闭/注销

发布于 2024-08-26 08:39:15 字数 298 浏览 4 评论 0原文

我编写了一个 C# Windows 窗体应用程序,而不是一个具有无限循环运行的后台线程的服务(它仅在用户登录并具有图形用户界面时使用)。

然而,当我尝试关闭 Windows (7) 时,它告诉我该程序正在阻止它关闭或注销,并询问我是否要强制关闭。

现在,我的程序是否有可能意识到(获取处理程序)Windows 试图退出它或注销?

所以,我需要的是让应用程序在Windows尝试退出时实现。

提前致谢。

编辑:感谢您的好建议!如果表单关闭事件有 CANCEL 事件处理程序,是否可以以任何方式使用该想法?

I have written a C# Windows Forms application, not a service (it is only used when the user is logged in and has a graphical user interface) that has a background thread running in an infinite loop.

When I try shutting down Windows (7) however, it tells me the program is preventing it from shutting down or logging off and asks me whether I want to force a shutdown.

Now, is there any possibility for my program to become aware (get a handler) of Windows trying to quit it or to log off?

So, what I need is to make the application realize when Windows tries to quit.

Thanks in advance.

EDIT: Thanks for the great advice! Is it in any way possible to use the idea with the form closing event if it has a CANCEL event handler?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

清欢 2024-09-02 08:39:15
public Form1()
{
    InitializeComponent();

    this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Or any of the other reasons suitable for what you want to accomplish
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        //Stop your infinite loop
    }
}
public Form1()
{
    InitializeComponent();

    this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
}

void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // Or any of the other reasons suitable for what you want to accomplish
    if (e.CloseReason == CloseReason.WindowsShutDown)
    {
        //Stop your infinite loop
    }
}
似梦非梦 2024-09-02 08:39:15

您将该线程称为“后台线程”,但它是否具有 IsBackground = true;
系统只会停止这样做的线程。

You call that thread a "background thread" but does it have IsBackground = true; ?
The system will only stop a thread that does.

讽刺将军 2024-09-02 08:39:15

我认为 Capture console exit C# 也应该在您的场景中可用。

除此之外,也许将线程设置为 后台线程

I think Capture console exit C# should also be usable in your scenario.

Apart from that, maybe it is sufficient to set up your thread as background thread?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文