专为你写的代码,供参考:
//搜索单元;
unit U_FrmSearch;
interface
uses
Windows, Messages, Classes, Forms, Controls, StdCtrls;
type
TSearchThread = class;
TFrmSearch = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
private
FSearchThread: TSearchThread;
proceduredo
OnSearchTerminate(Sender: TObject);
end;
TSearchThread = class(TThread)
private
FDelay: Integer;
FSearchFrm: TFrmSearch;
FMainHandle: THandle;
protected
procedure CreateAForm;
procedure Execute;
override;
public
constructor Create(CreateSuspended: Boolean;
AHandle: THandle);
end;
const
//自定义消息常量;
MsgOnSearch = WM_USER + 1;
implementation
{$R *.DFM}
procedure TFrmSearch.Button1Click(Sender: TObject);
begin
if not Assigned(FSearchThread) then
Exit;
if FSearchThread.Suspended then
FSearchThread.Resume
else
FSearchThread.Suspend;
end;
procedure TFrmSearch.DoOnSearchTerminate(Sender: TObject);
begin
if Assigned(FSearchThread) then
FSearchThread.OnTerminate := nil;
Close;
end;
{ TSearchThread }
constructor TSearchThread.Create(CreateSuspended: Boolean;
AHandle: THandle);
begin
inherited Create(CreateSuspended);
FMainHandle := AHandle;
FreeOnTerminate := True;
FSearchFrm := nil;
end;
procedure TSearchThread.CreateAForm;
begin
//创建搜索窗体;
if not Assigned(FSearchFrm) then
begin
FSearchFrm := TFrmSearch.Create(nil);
FSearchFrm.FSearchThread := Self;
//线程终止时释放搜索窗体;
OnTerminate := FSearchFrm.DoOnSearchTerminate;
FSearchFrm.Show;
end;
end;
procedure TSearchThread.Execute;
begin
FDelay := 0;
while not Terminateddo
begin
Inc(FDelay);
Sleep(100);
//DoSearch;
if FDelay = 30 then
Synchronize(CreateAForm);
//向创建搜索线程的主线程发消息;
PostMessage(FMainHandle, MsgOnSearch, FDelay, 0);
end;
end;
end.
//主单元;
unit U_main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls, U_FrmSearch;
type
TForm1 = class(TForm)
Button1: TButton;
Button2: TButton;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
procedure FormClose(Sender: TObject;
var Action: TCloseAction);
private
proceduredo
MsgOnSearch(var Msg: TMessage);
message MsgOnSearch;
public
SearchThread: TSearchThread;//搜索线程
end;
var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.Button1Click(Sender: TObject);
begin
//创建搜索线程;
if not Assigned(SearchThread) then
SearchThread := TSearchThread.Create(False, Handle);
end;
procedure TForm1.DoMsgOnSearch(var Msg: TMessage);
begin
//响应搜索线程的消息;
Caption := IntToStr(Msg.WParam);
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
//终止搜索线程;
if Assigned(SearchThread) then
begin
SearchThread.Terminate;
SearchThread := nil;
end;
end;
procedure TForm1.FormClose(Sender: TObject;
var Action: TCloseAction);
begin
if not Assigned(SearchThread) then
Exit;
if not SearchThread.Suspended then
SearchThread.Resume;
SearchThread.Terminate;
end;
end.