delphi中时间控制

用TTimer的思路有点问题。

请参考以下思路:

窗体建立时,记录GetTickCount值(关于GetTickCount,请Google),然后,捕捉鼠标键盘消息,如有发送到本窗体的鼠标键盘消息,则重

新记录GetTickCount值,如无,则计算当前GetTickCount值减去原值是否大于规定时间,如大于则Close。

例子如下:

//思路是这样的,但我的代码并不一定全面。

窗体类的

private部分,放一个全局变量:

FX : Cardinal;

在窗体上放一个ApplicationEvents控件,在其OnMessage中写代码:

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;

var Handled: Boolean);

begin

if (GetTickCount - FX) > 1000 * 60 * 2 then Self.Close;//如超时2分钟则关本窗体

if (Msg.message = WM_MouseMove)//如果鼠标在窗体范围内移动

or (Msg.message = WM_KeyDown) //或者键盘按下

then FX := GetTickCount; //则重新计时

end;

procedure TForm1.FormCreate(Sender: TObject);

begin

FX := GetTickCount;

end;

////////////////////////////////////

请看一下我的实现:(虽然还是用了TTimer,但需注意,在我的代码里,TTimer不是主角)

以下是全部代码:

unit Unit1;

interface

uses

Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,

Dialogs, StdCtrls, AppEvnts, ExtCtrls;

type

TForm1 = class(TForm)

Button1: TButton;

Edit1: TEdit;

ApplicationEvents1: TApplicationEvents;

Label1: TLabel;

Timer1: TTimer;

procedure FormCreate(Sender: TObject);

procedure ApplicationEvents1Message(var Msg: tagMSG;

var Handled: Boolean);

procedure Timer1Timer(Sender: TObject);

private

{ Private declarations }

FX : Cardinal;/////////////////////////<-----------------------

public

{ Public declarations }

end;

var

Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.FormCreate(Sender: TObject);

begin

Self.Caption := '本窗体如果客户区无鼠标键盘操作则10秒后关闭';//包括鼠标在客户区移动

Button1.Caption := '鼠标测试';

Edit1.Text := '按键输入';

FX := GetTickCount; ////赋初值

Timer1.Interval := 1;

end;

procedure TForm1.ApplicationEvents1Message(var Msg: tagMSG;

var Handled: Boolean);

begin

if (GetTickCount - FX) > 1000 * 10 then Self.Close;//如超时10秒则关本窗体

if ((Msg.message >= WM_MouseFirst) and (Msg.message <= WM_MouseLast))//如果有鼠标消息

or ((Msg.message >= WM_KeyFirst) and (Msg.message <= WM_KeyLast))//或者有键盘消息

then FX := GetTickCount; //则重新计时

end;

procedure TForm1.Timer1Timer(Sender: TObject);//显示倒计时

begin

Label1.Caption := InttoStr(10 - (GetTickCount-FX) div 1000);

end;

end.