LASTINPUTINFO lii = { sizeof(lii) };
GetLastInputInfo(&lii);
DWORD idleMs = GetTickCount() - lii.dwTime; // 閒置毫秒數
BOOL IdleUIInit(); // 安裝鍵盤/滑鼠 Hook
void IdleUITerm(); // 卸載 Hook
DWORD IdleUIGetLastInputTime(); // 取得最後輸入 tick count
HHOOK g_hKbdHook, g_hMouseHook;
DWORD g_lastInput = 0;
LRESULT CALLBACK KbdHook(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HC_ACTION) g_lastInput = GetTickCount();
return CallNextHookEx(g_hKbdHook, nCode, wParam, lParam);
}
LRESULT CALLBACK MouseHook(int nCode, WPARAM wParam, LPARAM lParam) {
if (nCode == HC_ACTION) g_lastInput = GetTickCount();
return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
}
BOOL IdleUIInit() {
HINSTANCE hInst = GetModuleHandle(nullptr);
g_hKbdHook = SetWindowsHookEx(WH_KEYBOARD, KbdHook, hInst, 0);
g_hMouseHook = SetWindowsHookEx(WH_MOUSE, MouseHook, hInst, 0);
return g_hKbdHook && g_hMouseHook;
}
void CMainFrame::OnTimer(UINT) {
DWORD idleSec = (GetTickCount() - IdleUIGetLastInputTime()) / 1000;
CString s; s.Format(L"閒置 %d 秒", idleSec);
Invalidate(); // 觸發重繪
}
void CMainFrame::OnPaint() {
CPaintDC dc(this);
CString s; s.Format(L"鍵盤/滑鼠閒置 %d 秒",
(GetTickCount() - IdleUIGetLastInputTime())/1000);
CRect r; GetClientRect(&r);
dc.DrawText(s, &r, DT_CENTER|DT_VCENTER|DT_SINGLELINE);
}
TestIdleUI.exe
IdleUI.dll
啟動測試程式,滑鼠/鍵盤不動計數器遞增,動一下歸零。