SetWaitableTimer 中回調函數後面的指針參數, 將被傳遞給 APC 函數的第一個參數;
作為指針它可以攜帶任何數據, 這裡讓它攜帶了一個坐標點(鼠標點擊窗體的位置), 下例效果圖:
代碼文件:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
procedure FormDestroy(Sender: TObject);
procedure FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
hTimer: THandle;
pt: TPoint;
{APC 函數}
procedure TimerAPCProc(lpArgToCompletionRoutine: Pointer; dwTimerLowValue: DWord;
dwTimerHighValue: DWord); stdcall;
var
UTCFileTime,LocalFileTime: TFileTime;
SystemTime: TSystemTime;
DateTime: TDateTime;
pt2: TPoint;
begin
UTCFileTime.dwLowDateTime := dwTimerLowValue;
UTCFileTime.dwHighDateTime := dwTimerHighValue;
FileTimeToLocalFileTime(UTCFileTime, LocalFileTime);
FileTimeToSystemTime(LocalFileTime, SystemTime);
DateTime := SystemTimeToDateTime(SystemTime);
pt2 := PPoint(lpArgToCompletionRoutine)^; {接受指針參數}
Form1.Canvas.Lock;
Form1.Canvas.TextOut(pt2.X, pt2.Y, DateTimeToStr(DateTime));
Form1.Canvas.Unlock;
SleepEx(INFINITE, True);
end;
{線程入口函數}
function MyThreadFun(p: Pointer): Integer; stdcall;
var
DueTime: Int64;
begin
DueTime := 0;
{參數 @pt 在這裡是鼠標點擊窗體時的坐標結構的指針, 它將傳遞給 APC 函數的第一個參數}
if SetWaitableTimer(hTimer, DueTime, 1000, @TimerAPCProc, @pt, False) then
begin
SleepEx(INFINITE, True);
end;
Result := 0;
end;
{建立 WaitableTimer 對象和線程}
procedure TForm1.FormMouseDown(Sender: TObject; Button: TMouseButton;
Shift: TShiftState; X, Y: Integer);
var
ID: DWord;
begin
pt := Point(X,Y); {在這裡個全局的坐標點賦值}
if hTimer = 0 then hTimer := CreateWaitableTimer(nil, True, nil);
CreateThread(nil, 0, @MyThreadFun, nil, 0, ID);
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle(hTimer);
end;
end.
窗體文件:
object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClIEntHeight = 135
ClIEntWidth = 195
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
OnMouseDown = FormMouseDown
PixelsPerInch = 96
TextHeight = 13
end