在线程中使用定时器的例子!

时间:2022-10-09 00:15:04
在CSDN中找到的例子,自己测试了一下。
unit Unit1;interfaceuses  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  Dialogs, StdCtrls, ExtCtrls;type   TCheckExternalButtonThread = class(TThread)     private    { Private declarations }      FTimer:TTimer;      procedure TimerProc(Sender: TObject);      procedure KillIt;    protected      procedure Execute;override;    public      ThreadNo:THandle;      constructor Create();    end;  TForm1 = class(TForm)    Memo1: TMemo;    Button1: TButton;    Button2: TButton;    procedure Button1Click(Sender: TObject);    procedure Button2Click(Sender: TObject);  private    { Private declarations }  public    { Public declarations }  end;var  Form1: TForm1;  ss:TCheckExternalButtonThread ;implementation{$R *.dfm}constructor TCheckExternalButtonThread.Create();begin    inherited Create(False);end;procedure TCheckExternalButtonThread.KillIt;begin  PostThreadMessage(ThreadNo,WM_QUIT,0,0);end;procedure TCheckExternalButtonThread.TimerProc(Sender: TObject);begin  Form1.Memo1.Lines.Add('asdasf');end;procedure TCheckExternalButtonThread.Execute;var MsgRec:TMsg;begin  FTimer:=TTimer.Create(nil);  try      FTimer.Enabled:=True;//需要用的时候Enabled设置为True即可。      FTimer.OnTimer:=TimerProc;      FTimer.Interval:=100;      while GetMessage(MsgRec, 0, 0, 0) do begin        TranslateMessage(MsgRec);        DispatchMessage(MsgRec)      end;      Terminate;  finally    FTimer.Free;  end;end;procedure TForm1.Button1Click(Sender: TObject);begin ss:=TCheckExternalButtonThread.Create; ss.ThreadNo:=ss.ThreadID;end;procedure TForm1.Button2Click(Sender: TObject);begin ss.KillIt;end;end.