代碼文件:
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
procedure FormProc; {准備給線程使用的方法}
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
hThread: THandle;
{線程入口函數}
function MyThreadFun(p: Pointer): DWord; stdcall;
begin
Form1.FormProc; {調用 TForm1 類的方法}
Result := 99; {這個返回值將成為線程的退出代碼, 99 是我隨意給的數字}
end;
{TForm1 的方法, 本例中是給線程的入口函數調用的}
procedure TForm1.FormProc;
var
i: Integer;
begin
for i := 0 to 200000 do
begin
with Form1.Canvas do begin
Lock;
TextOut(10, 10, IntToStr(i));
Unlock;
end;
end;
end;
{建立並執行線程}
procedure TForm1.Button1Click(Sender: TObject);
var
ID: DWord;
begin
hThread := CreateThread(nil, 0, @MyThreadFun, nil, 0, ID);
end;
{獲取線程的退出代碼, 並判斷線程是否退出}
procedure TForm1.Button2Click(Sender: TObject);
var
ExitCode: DWord;
begin
GetExitCodeThread(hThread, ExitCode);
if hThread = 0 then
begin
Text := '線程還未啟動';
Exit;
end;
if ExitCode = STILL_ACTIVE then
Text := Format('線程退出代碼是: %d, 表示線程還未退出', [ExitCode])
else
Text := Format('線程已退出, 退出代碼是: %d', [ExitCode]);
end;
end.