程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> Delphi >> 多線程編程(17) - 多線程同步之WaitableTimer(等待定時器對象)[續三](2)

多線程編程(17) - 多線程同步之WaitableTimer(等待定時器對象)[續三](2)

編輯:Delphi

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

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved