判断空闲时间是否超过阀值

如何使用的示例代码

void CRealLoginDlg::OnTimer(UINT_PTR nIDEvent)
{
	DWORD lastTickTock = IdleTrackerGetLastTickCount();
	DWORD nowTickTock = GetTickCount();
	DWORD differSeconds= (nowTickTock - lastTickTock)/1000;

	//if idle time is 5s,send login message!
	if (differSeconds>=5 && m_isStartLogin==false && m_ctlRememberPWD.GetCheck()==BST_CHECKED)
	{
		PostMessageW(WM_AUTO_LOGIN);
	}

	CDialogEx::OnTimer(nIDEvent);
}



依赖项

头文件清单

#pragma once

BOOL IdleTrackerInit();
void IdleTrackerTerm();
DWORD IdleTrackerGetLastTickCount();


源文件清单

#include "StdAfx.h"
#include "IdleTracker.h"

HHOOK 	g_hHkKeyboard = NULL;	// handle to the keyboard hook
HHOOK 	g_hHkMouse = NULL;	// handle to the mouse hook
DWORD	g_dwLastTick = 0;	// tick time of last input event
LONG	g_mouseLocX = -1;	// x-location of mouse position
LONG	g_mouseLocY = -1;	// y-location of mouse position
/**
 * Get tick count of last keyboard or mouse event
 **/
DWORD IdleTrackerGetLastTickCount()
{
	return g_dwLastTick;
}

/**
 * Keyboard hook: record tick count
 **/
LRESULT CALLBACK KeyboardTracker(int code, WPARAM wParam, LPARAM lParam)
{
	if (code==HC_ACTION) {
		g_dwLastTick = GetTickCount();
	}
	return ::CallNextHookEx(g_hHkKeyboard, code, wParam, lParam);
}

/**
 * Mouse hook: record tick count
 **/
LRESULT CALLBACK MouseTracker(int code, WPARAM wParam, LPARAM lParam)
{
	if (code==HC_ACTION) {
		MOUSEHOOKSTRUCT* pStruct = (MOUSEHOOKSTRUCT*)lParam;
		//we will assume that any mouse msg with the same locations as spurious
		if (pStruct->pt.x != g_mouseLocX || pStruct->pt.y != g_mouseLocY)
		{
			g_mouseLocX = pStruct->pt.x;
			g_mouseLocY = pStruct->pt.y;
			g_dwLastTick = GetTickCount();
		}
	}
	return ::CallNextHookEx(g_hHkMouse, code, wParam, lParam);
}

/**
 * Initialize DLL: install kbd/mouse hooks.
 **/
BOOL IdleTrackerInit()
{
	if (g_hHkKeyboard == NULL) {
		g_hHkKeyboard = SetWindowsHookEx(WH_KEYBOARD, KeyboardTracker, NULL,  GetCurrentThreadId() );
	}
	if (g_hHkMouse == NULL) {
		g_hHkMouse = SetWindowsHookEx(WH_MOUSE, MouseTracker, NULL,  GetCurrentThreadId() );
	}

	_ASSERT(g_hHkKeyboard);
	_ASSERT(g_hHkMouse);

	g_dwLastTick = GetTickCount(); // init count

	if (!g_hHkKeyboard || !g_hHkMouse)
		return FALSE;
	else
		return TRUE;
}

/**
 * Terminate DLL: remove hooks.
 **/
void IdleTrackerTerm()
{
	BOOL bResult;
	if (g_hHkKeyboard)
	{
		bResult = UnhookWindowsHookEx(g_hHkKeyboard);
		_ASSERT(bResult);
		g_hHkKeyboard = NULL;
	}
	if (g_hHkMouse)
	{
		bResult = UnhookWindowsHookEx(g_hHkMouse);
		_ASSERT(bResult);
		g_hHkMouse = NULL;
	}
}


你可能感兴趣的:(判断空闲时间是否超过阀值)