代碼文件:unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Button3: TButton;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
var
hThread: THandle; {線程句柄}
num: Integer; {全局變量, 用於記錄隨機數}
{線程入口函數}
function MyThreadFun(p: Pointer): Integer; stdcall;
begin
while True do {假如線程不掛起, 這個循環將一直循環下去}
begin
num := Random(100);
end;
Result := 0;
end;
{建立並掛起線程}
procedure TForm1.Button1Click(Sender: TObject);
var
ID: DWord;
begin
hThread := CreateThread(nil, 0, @MyThreadFun, nil, CREATE_SUSPENDED, ID);
Button1.Enabled := False;
end;
{喚醒並繼續線程}
procedure TForm1.Button2Click(Sender: TObject);
begin
ResumeThread(hThread);
end;
{掛起線程}
procedure TForm1.Button3Click(Sender: TObject);
begin
SuspendThread(hThread);
end;
{下面是窗體代碼}
procedure TForm1.FormCreate(Sender: TObject);
begin
Timer1.Interval := 100;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Text := IntToStr(num);
end;
end.