給個範例, 要使用時就呼叫TFormTread.ExecuteThreadForm, 傳入form class即可
type
TFormThread = class(TThread)
private
FFormClass: TFormClass;
FForm: TForm;
FOldDestroy: TNotifyEvent;
protected
proceduredo
Destroy(Sender: TObject);
procedure Execute;
override;
public
class function ExecuteThreadForm(FormClass: TFormClass): TFormThread;
property Form: TForm read FForm;
end;
{ TFormThread }
procedure TFormThread.DoDestroy(Sender: TObject);
begin
if Assigned(FOldDestroy) then
FOldDestroy(Sender);
FForm := nil;
end;
procedure TFormThread.Execute;
begin
CoInitializeEx(nil, COINIT_APARTMENTTHREADED);
try
if FFormClass <> nil then
begin
FForm := FFormClass.Create(nil);
FOldDestroy := FForm.OnDestroy;
FForm.OnDestroy := Self.DoDestroy;
FForm.Show;
while (FForm <> nil) and not Terminateddo
Application.ProcessMessages;
if FForm <> nil then
FForm.Free;
end;
finally
CoUninitialize;
end;
FreeOnTerminate := True;
end;
class function TFormThread.ExecuteThreadForm(FormClass: TFormClass): TFormThread;
begin
Result := TFormThread.Create(True);
try
Result.FFormClass := FormClass;
Result.Resume;
except
Result.Free;
raise;
end;
end;