unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls;
type
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormDestroy(Sender: TObject);
procedure MyThreadTerminate(Sender: TObject);
procedure Timer1Timer(Sender: TObject);
private
FMyThread: TMyThread;
end;
var
Form1: TForm1;
implementation
{$R *.dfm}
procedure TForm1.Button1Click(Sender: TObject);
begin
if not Assigned(FMyThread) then begin
FMyThread := TMyThread.Create(True);
FMyThread.OnTerminate := MyThreadTerminate;
FMyThread.Resume;
end;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if Assigned(FMyThread) then begin
TerminateThread(FMyThread.Handle, 0);
FreeAndNil(FMyThread);
end;
end;
procedure TForm1.FormDestroy(Sender: TObject);
begin
FreeAndNil(FMyThread);
end;
procedure TForm1.MyThreadTerminate(Sender: TObject);
begin
MessageDlg('MyThread finished', mtInformation, [mbYes], 0);
Timer1.Enabled := True;
end;
procedure TForm1.Timer1Timer(Sender: TObject);
begin
Timer1.Enabled := False;
FreeAndNil(FMyThread);
end;
{ TMyThread }
procedure TMyThread.Execute;
begin
Sleep(10000); // долгая операция
end;
end.