為什麼是用等待函數來把關? 因為上面幾個等待函數也可以等待是否有 APC 函數想入列.
上面給出的幾個等待函數, 就 SleepEx 的參數最少, 先用它吧:
function SleepEx(
dwMilliseconds: DWord; {毫秒數}
bAlertable: BOOL {布爾值}
): DWord; stdcall;
//第一個參數和 Sleep 的那個參數是一樣的, 是線程等待(或叫掛起)的時間, 時間一到不管後面參數如何都會返回.
//第二個參數如果是 False, SleepEx 將不會關照 APC 函數是否入列;
//若是 True, 只要有 APC 函數申請, SleepEx 不管第一個參數如何都會把 APC 推入隊列並隨 APC 函數一起返回.
//注意: SetWaitableTimer 和 SleepEx 必須在同一個線程才可以.
本例效果圖:
代碼文件:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, ExtCtrls, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
hTimer: THandle;
{APC 函數(過程), 函數名和參數名可以不同, 格式必須如此}
procedure TimerAPCProc(lpArgToCompletionRoutine: Pointer; dwTimerLowValue: DWord;
dwTimerHighValue: DWord); stdcall;
begin
Form1.Text := IntToStr(StrToIntDef(Form1.Text, 0) + 1); {標題 + 1}
end;
procedure TForm1.Button1Click(Sender: TObject);
var
DueTime: Int64;
begin
hTimer := CreateWaitableTimer(nil, True, nil);
DueTime := 0;
if SetWaitableTimer(hTimer, DueTime, 0, @TimerAPCProc, nil, False) then
begin
SleepEx(INFINITE, True); {INFINITE 表示一直等}
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
CloseHandle(hTimer);
end;
end.
窗體文件:
object Form1: TForm1
Left = 0
Top = 0
Caption = 'Form1'
ClIEntHeight = 113
ClIEntWidth = 203
Color = clBtnFace
Font.Charset = DEFAULT_CHARSET
Font.Color = clWindowText
Font.Height = -11
Font.Name = 'Tahoma'
Font.Style = []
OldCreateOrder = False
PixelsPerInch = 96
TextHeight = 13
object Button1: TButton
Left = 64
Top = 48
Width = 75
Height = 25
Caption = 'Button1'
TabOrder = 0
OnClick = Button1Click
end
end