vc 阻止电脑休眠
主要是使用API SetThreadExecutionState
调用过这个API的线程不退出的话,系统就一直不会进入睡眠状态。
Demo,系统设置一分钟空闲就进入休眠状态,让线程运行2分钟
DWORD WINAPI ThreadProc(_In_ LPVOID lpParameter)
{
if (SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED |
ES_AWAYMODE_REQUIRED | ES_DISPLAY_REQUIRED) == NULL)
{
// try XP variant as well just to make sure
SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
} // if
for (int i = 0; i < 120; i++)
{
Sleep(1000);
OutputDebugString(_T("Thread running...\r\n"));
}
OutputDebugString(_T("Thread Exit...\r\n"));
return 0;
}
int APIENTRY _tWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPTSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_S3, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(IDC_S3));
CreateThread(NULL, 0, ThreadProc, NULL, 0, NULL);
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return (int) msg.wParam;
}
结果是3分钟后系统进入休眠。