【发布时间】:2016-10-12 14:59:06
【问题描述】:
我正在开发一个多线程应用程序 (RAD Studio XE5)。在应用程序开始时,我创建了一个线程,该线程将与主窗体一样长。
我能够将消息从线程发送到在我的应用程序中创建的任何表单,但是我找不到相反的方法,将消息从主 VCL 线程发送到工作线程。
创建主窗体时,我创建工作线程并将句柄复制到公共变量中:
serverThread := TMyThread.Create(True, ServerPort + 1);
serverThreadHandle := serverThread.Handle; // SAVE HANDLE
serverThread.Start;
然后(从另一个表单 FrmSender)我向线程发送一条消息:
PostMessage(uMain.serverThreadHandle, UM_LOC_VCLMSG, UM_LOC_VCLMSG, Integer(PStrListVar));
这是线程的执行过程:
procedure TMyThread.Execute;
var
(..)
vclMSG : TMsg;
str1, str2 : string;
(..)
begin
while not(Terminated) do
begin
Sleep(10);
if Assigned(FrmSender) then
if FrmSender.HandleAllocated then
if PeekMessage(vclMSG, FrmSender.Handle, 0, 0, PM_NOREMOVE) then
begin
if vclMSG.message = UM_LOC_VCLMSG then
begin
try
pStrListVar := pStrList(vclMSG.lParam);
str1 := pStrListVar^.Strings[0];
str2 := pStrListVar^.Strings[1];
finally
Dispose(pStrListVar);
end;
end;
end;
(.. do other stuff ..)
end;
end;
但是 PeekMessage() 永远不会返回 true,就好像它从未收到任何消息一样。我尝试将参数更改为 PeekMessage():
PeekMessage(vclMSG, 0, 0, 0, PM_NOREMOVE);
但没有结果。 有什么想法吗?
【问题讨论】:
-
您不会 PostMessage 到线程句柄,阅读 PostMessage 的文档会有所帮助。
-
忘了说线程是从TThread类派生的
标签: multithreading delphi vcl