我正在编写仅当 PC 上没有人类活动时才需要运行的代码,例如当屏幕保护程序运行时。关于如何在 Windows 下用 C++ 执行此操作有什么建议吗?
@talnicolas,只是为了使用未使用的资源,有多少次人们让计算机打开但他们在另一个地方?
您可以使用GetLastInputInfo http://msdn.microsoft.com/en-us/library/windows/desktop/ms646302(v=vs.85).aspx检查用户闲置的时间(没有移动鼠标或在键盘上输入内容)以及SystemParametersInfo http://msdn.microsoft.com/en-us/library/windows/desktop/ms724947%28v=vs.85%29.aspx检查屏幕保护程序是否处于活动状态。
Example
#define WINDOWS_LEAN_AND_MEAN
#include <windows.h>
#include <iostream>
// do something after 10 minutes of user inactivity
static const unsigned int idle_milliseconds = 60*10*1000;
// wait at least an hour between two runs
static const unsigned int interval = 60*60*1000;
int main() {
LASTINPUTINFO last_input;
BOOL screensaver_active;
// main loop to check if user has been idle long enough
for (;;) {
if ( !GetLastInputInfo(&last_input)
|| !SystemParametersInfo(SPI_GETSCREENSAVERACTIVE, 0,
&screensaver_active, 0))
{
std::cerr << "WinAPI failed!" << std::endl;
return ERROR_FAILURE;
}
if (last_input.dwTime < idle_milliseconds && !screensaver_active) {
// user hasn't been idle for long enough
// AND no screensaver is running
Sleep(1000);
continue;
}
// user has been idle at least 10 minutes
do_something();
// done. Wait before doing the next loop.
Sleep(interval);
}
}
请注意,我在 Linux 机器上编写了该代码,因此无法对其进行测试。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)