如果你的程序是有GUI的话
可以截获键盘鼠标消息。是控制台或者是服务形态的话,我就不知道了
下面是截获键盘鼠标消息的例子:
unit Unit1;
interface
uses
DateUtils, ExtCtrls,
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs;
type
TForm1 = class(TForm)
procedure FormCreate(Sender: TObject);
private
Oclock:TTimer;
IdleTimeLimited:Integer;
LastActTime:TDateTime;
procedure ApplicationEventsMessage(var Msg: tagMSG;
var Handled: Boolean);
procedure TimerTimer(Sender: TObject);
{ Private declarations }
public
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.ApplicationEventsMessage(var Msg: tagMSG;
var Handled: Boolean);
begin
//如果已经定义主系统的Application的OnMessage事件则先调用;
//处理键盘、鼠标消息
if ((Msg.message >= WM_KEYFIRST) and (Msg.message <= WM_KEYLAST)) or
((Msg.message >= WM_MOUSEFIRST) and (Msg.message <= WM_MOUSELAST))then
LastActTime := now;
end;
procedure TForm1.TimerTimer(Sender: TObject) ;
begin
//如果键盘、鼠标在指定的时间内没有消息,调用处理事件
if SecondsBetween(now,LastActTime) > IdleTimeLimited then Begin
LastActTime := now;
ShowMessage('本程序未活动时间超过'+IntToStr(IdleTimeLimited)+'秒!');
//你可以在这写关闭程序事件
end;
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
LastActTime := now;
IdleTimeLimited := 3;
Oclock := TTimer.Create(self);
Oclock.Enabled := True;
//设置时间控件的时间事件
Oclock.OnTimer := TimerTimer;
Application.OnMessage := ApplicationEventsMessage;
end;
end.