gpt4 book ai didi

forms - 在 Delphi 中线程打开表单

转载 作者:行者123 更新时间:2023-12-03 14:42:22 25 4
gpt4 key购买 nike

我想从线程创建新的表单实例(并显示它们)。但它似乎卡住了我的应用程序和我的线程(我的线程变成了非同步线程,并且它卡住了我的应用程序)。

像这样(但它并没有达到我想要的效果)

procedure a.Execute;
var frForm:TForm;
B:TCriticalSection;
begin
b:=TCriticalSection.Create;
while 1=1 do
begin
b.Enter;

frForm:=TForm.Create(Application);
frForm.Show;
b.Leave;
sleep(500); //this sleep with sleep my entire application and not only the thread.
//sleep(1000);
end;
end;

我不想使用Classes.TThread.Synchronize方法

最佳答案

TThread.Synchronize() 是最简单的解决方案:

procedure a.Execute;
begin
while not Terminated do
begin
Synchronize(CreateAndShowForm);
Sleep(500);
end;
end;

procedure a.CreateAndShowForm;
var
frForm:TForm;
begin
frForm:=TForm.Create(Application);
frForm.Show;
end;

如果您使用的是现代版本的 Delphi,并且不需要等待 TForm 创建完成才让线程继续,您可以使用 TThread.Queue() 相反:

procedure a.Execute;
begin
while not Terminated do
begin
Queue(CreateAndShowForm);
Sleep(500);
end;
end;

更新:如果您想使用 PostMessage(),最安全的选择是将消息发布到 TApplication 窗口或通过AllocateHWnd()创建的专用窗口,例如:

const
WM_CREATE_SHOW_FORM = WM_USER + 1;

procedure TMainForm.FormCreate(Sender: TObject);
begin
Application.OnMessage := AppMessage;
end;

procedure TMainForm.AppMessage(var Msg: TMsg; var Handled: Boolean);
var
frForm:TForm;
begin
if Msg.message = WM_CREATE_SHOW_FORM then
begin
Handled := True;
frForm := TForm.Create(Application);
frForm.Show;
end;
end;

procedure a.Execute;
begin
while not Terminated do
begin
PostMessage(Application.Handle, WM_CREATE_SHOW_FORM, 0, 0);
Sleep(500);
end;
end;

.

const
WM_CREATE_SHOW_FORM = WM_USER + 1;

var
ThreadWnd: HWND = 0;

procedure TMainForm.FormCreate(Sender: TObject);
begin
ThreadWnd := AllocateHWnd(ThreadWndProc);
end;

procedure TMainForm.FormDestroy(Sender: TObject);
begin
DeallocateHwnd(ThreadWnd);
ThreadWnd := 0;
end;

procedure TMainForm.ThreadWndProc(var Message: TMessage);
var
frForm:TForm;
begin
if Message.Msg = WM_CREATE_SHOW_FORM then
begin
frForm := TForm.Create(Application);
frForm.Show;
end else
Message.Result := DefWindowProc(ThreadWnd, Message.Msg, Message.WParam, Message.LParam);
end;

procedure a.Execute;
begin
while not Terminated do
begin
PostMessage(ThreadWnd, WM_CREATE_SHOW_FORM, 0, 0);
Sleep(500);
end;
end;

关于forms - 在 Delphi 中线程打开表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9719714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com