如何在 winforms 应用程序中优雅地处理休眠/睡眠模式?

发布于 2024-09-13 01:45:11 字数 236 浏览 2 评论 0 原文

我正在使用 C# 在 .net 中编写一个 Windows 窗体应用程序。

我遇到一个问题,如果我的程序在计算机进入睡眠和/或休眠状态时运行(我目前不确定是哪一个或两者导致问题),当机器再次唤醒时程序只是挂起。退出它的唯一方法是从任务管理器中终止该进程。

出于显而易见的原因,这不是我希望程序运行的方式。即使我只是在程序进入这些状态时关闭程序,那也没关系,但我不太确定如何做到这一点,或者是否有一种更优雅的方式来处理这个问题。

I am writing a windows form application in .net using C#.

I am running into a problem that if my program is running when the computer goes into the sleep and/or hibernate state (I am not sure at this time which one, or if both, cause the problem), when the machine wakes up again the program just hangs. The only way to exit out of it is to kill the process from the task manager.

This is, for obvious reasons, not the way I want the program to function. Even if I just shut the program down when it goes into these states, that would be fine, but I am not quite sure how to do this or if there is a more graceful way altogether of handling this.

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

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

发布评论

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

评论(3

明天过后 2024-09-20 01:45:11

您需要:

using Microsoft.Win32;   

这是代码:

 void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
    {
        if(e.Mode == PowerModes.Suspend)
        {
            this.GracefullyHandleSleep();
        }
    }

这就是我所使用的。

You need:

using Microsoft.Win32;   

And this is the code:

 void SystemEvents_PowerModeChanged(object sender, PowerModeChangedEventArgs e)
    {
        if(e.Mode == PowerModes.Suspend)
        {
            this.GracefullyHandleSleep();
        }
    }

This is what I went with.

2024-09-20 01:45:11

处理这些事件可能是一种解决方法。但在应用这种解决方法之前,我会尝试弄清楚当操作系统进入休眠状态时应用程序正在做什么。

尽管应用程序只是闲置,但仍发生挂起?

应用程序是否正在执行某种不应被中断的低级工作(与设备驱动程序或外部硬件的通信)?

该应用程序是否使用某种网络连接?

Handling those events may be a work-around. But before applying this kind of work-around I'd try to figure out what the application was doing when the OS went into hibernate.

Occurs hanging although application was just idle?

Is the application doing some kind of low-level work (communication with device drivers or external hardware) that should not be interrupted?

Does the application use some kind of network connection?

高冷爸爸 2024-09-20 01:45:11

这篇文章介绍了监听这些事件。您必须执行类似 override WndProc 并监听 PBT_APMSUSPEND 事件。

This article covers listening for those events. You'll have to do something like override WndProc and listen for PBT_APMSUSPEND events.

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