防止Windows在我的程序运行时进入睡眠状态? [英] Prevent windows from going into sleep when my program is running?

查看:63
本文介绍了防止Windows在我的程序运行时进入睡眠状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我的程序运行时,我必须阻止 Windows 进入睡眠状态.

I have to stop windows from going into sleep when my program is running.

而且我不仅想阻止睡眠定时器,我还想取消睡眠事件,如果我按下睡眠按钮或以任何其他方式主动告诉计算机进入睡眠状态.因此 SetThreadExecutionState 是不够的.

And I don't only want to prevent the sleep-timer, I also want to cancel the sleep-event if I press the sleep-button or in any other way actively tell the computer to sleep. Therefore SetThreadExecutionState is not enough.

或者...我实际上不必完全阻止睡眠,只需延迟 5-10 秒即可让我的程序完成任务.

Or...I don't actually have to prevent the sleep completely, only delay it 5-10sec to allow my program to finish a task.

(我知道这是不好的程序行为,但仅供个人使用.)

(I know that this is bad program behavior but it's only for personal use.)

推荐答案

我在使用通过 USB 连接的硬件设备时遇到了这样的问题.XP/Vista 会在...中途睡眠/休眠,你说得很好,当它恢复时它可以继续.如果硬件仍然连接!用户习惯于随时拔出电缆.

I had a problem like this with a hardware device connected via usb. XP /Vista would sleep/hibernate right in the middle of ... Great you say, when it resumes it can just continue. If the hardware is still connected!!! Users have the habit of pulling cables out whenever they feel like it.

你需要处理 XP 和 Vista

You need to handle XP and Vista

在 XP 下捕获 WM_POWERBROADCAST 并查找 PBT_APMQUERYSUSPEND wparam.

Under XP trap the WM_POWERBROADCAST and look for the PBT_APMQUERYSUSPEND wparam.

   // See if bit 1 is set, this means that you can send a deny while we are busy
   if (message.LParam & 0x1)
   {
      // send the deny message
      return BROADCAST_QUERY_DENY;
   } // if
   else
   {
      return TRUE;
   } // else

在Vista下像这样使用SetThreadExecutionState

Under Vista use SetThreadExecutionState like this

// try this for vista, it will fail on XP
if (SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED) == NULL)
{
   // try XP variant as well just to make sure 
   SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
}  // if 

当您的应用完成后将其恢复正常

and when you app has finished set it back to normal

// set state back to normal
SetThreadExecutionState(ES_CONTINUOUS);

这篇关于防止Windows在我的程序运行时进入睡眠状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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