我也遇到过,就说说我的做法吧,与大家交流一下。
线程部分
TMyThread = class(TThread)
private
protected
procedure Execute;
override;
public
end;
procedure TMyThread.Execute;
begin
...
while truedo
begin
if Terminated then
break;
//退出循环
...
end;
SendMessage(form1.handle,WM_USER+1,0,0);
//发送消息给窗体,关闭它
end;
窗体部分
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs;
type
TForm1 = class(TForm)
procedure FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
procedure FormShow(Sender: TObject);
private
MyThreadTerminated :boolean;
{ Private declarations }
public
MyThread:TMyThread;
procedure MyThreadEnd(var Msg: TMsg);
message WM_USER+1;
{ Public declarations }
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.FormCloseQuery(Sender: TObject;
var CanClose: Boolean);
begin
if not MyThreadTerminated then
//线程还在运行,不能关闭,停止线程运行
begin
CanClose:=false;
MyThread.Terminate;
end;
end;
procedure TForm1.FormShow(Sender: TObject);
begin
MyThreadTerminated :=false;
MyThread:= TMyThread.create(false);
end;
procedure TForm1.MyThreadEnd(var Msg: TMsg);
//关闭窗体
begin
MyThreadTerminated:=true;
close;
end;
end.
另外,Windows有一种方法可能在程序中运行一个线程,并且等待线程结束,类似于
创建进程,等待进程结束一个。具体实现代码如下:
proceduredo
MyThread;
var
Msg: TMsg;
begin
FThread := TMyThread.Create(false);
while Assigned(FThread)do
while PeekMessage(Msg, 0, 0, 0, PM_REMOVE)do
begin
TranslateMessage(Msg);
DispatchMessage(Msg);
end;
end;