系统空闲时间检测 Idle
我们知道,当用户超过一定的时间没有输入之后,Windows就会启动屏幕保护功能,那么在程序中如何做到这一点呢?就是说我如何检测到用户多久没有输入呢?大家知道,在Windows中有一个Hook技术,就是钩子,我们利用Hook技术,Hook键盘和鼠标,这样就可以知道用户有没有输入了!因此,我们可以修改Timer控件,继承下来就可以了:
用法:
if IdleTimer1.Snooze>6000 then
ShowMessage('用户已经有6秒钟没有输入了!');
///FileName:IdleTimer.Pas
unit IdleTimer;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
ExtCtrls;
type
TIdleTimer = class(TTimer)
private
function GetSnooze: Longint;
procedure SetSnooze(const Value: Longint);
{ Private declarations }
protected
{ Protected declarations }
public
{ Public declarations }
constructor Create(AOwner:TComponent);override;
destructor Destroy;override;
property Snooze:Longint read GetSnooze write SetSnooze;
published
{ Published declarations }
end;
procedure Register;
implementation
var
Instances:integer;
ElapsedTime:Longint;
whKeyBoard,whMouse:HHook;
procedure Register;
begin
RegisterComponents('System', [TIdleTimer]);
end;
{ TIdleTimer }
function MouseHookCallBack(Code:integer;Msg:lParam;MouseHook:wParam):DWORD;stdcall;
begin
if Code>=0 then ElapsedTime :=GetTickCount;
Result := CallNextHookEx(whMouse,Code,Msg,MouseHook);
end;
function KeyBoardCallBack(Code:integer;Msg:word;KeyBoardHook:Longint):LongInt;stdcall;
begin
if Code>=0 then ElapsedTime :=GetTickCount;
Result := CallNextHookEx(whKeyBoard,Code,Msg,KeyBoardHook);
end;
constructor TIdleTimer.Create(AOwner: TComponent);
function GetModuleHandleFromInstance:THandle;
var
s:array[0..512] of char;
begin
GetModuleFileName(HInstance,s,SizeOf(s)-1);
Result :=GetModuleHandle(s);
end;
begin
inherited Create(AOwner);
Inc(Instances);
if Instances =1 then begin
ElapsedTime :=GetTickCount;
whMouse := SetWindowsHookEx(WH_MOUSE,@MouseHookCallback,GetModuleHandleFromInstance,0);
whKeyBoard :=SetWindowsHookEx(WH_KEYBOARD,@KeyBoardCallBack,GetModuleHandleFromInstance,0);
end;
end;
destructor TIdleTimer.Destroy;
begin
Dec(Instances);
if Instances =0 then begin
UnhookWindowsHookEx(whKeyBoard);
UnhookWindowsHookEx(whMouse);
end;
inherited;
end;
function TIdleTimer.GetSnooze: Longint;
begin
Result:= GetTickCount - ElapsedTime;
end;
procedure TIdleTimer.SetSnooze(const Value: Longint);
begin
ElapsedTime := GetTickCount + Value;
end;
end.