在线程里面通讯应该用PostThreadMessage来代替PostMessage
我写了一个例子供参考
一个form 两个线程类TReceiveThread和TSendThread
在form中定义
var
ReceiveHandle,ReceiveHandle:Thandle;
AReceiveThread:TReceiveThread;
ASendThread:TSendThread;
const
WM_MYMESSAGE=WM_USER+101;
AReceiveThread:=TReceiveThread.Create(false);
Receivehandle:=AReceiveThread.ThreadID;
ASendThread:=TSendThread.Create(false);
Sendhandle:=ASendThread.ThreadID;
在TSendThread的Execute中写入
PostThreadMessage(Receivehandle,WM_MYMESSAGE,0,0);
在TReceiveTHread的published定义
procedure ReceiveMessage(var Msg:TMessage);Message WM_MYMESSAGE;
procedure TReceiveThread.ReceiveMessage(var Msg:TMessage);
var
i:integer;
begin
MessageBox(self.Handle,PChar('收到消息'),PChar('收到消息'),mb_Ok);
end;
在Execute中写入
var
Msg:TMsg;
DMsg: TMessage;
begin
{ Place thread code here}
// while truedo
while not Terminateddo
begin
Sleep(10);
// 释放CPU资源
if PeekMessage(Msg,0,0,0,PM_REMOVE) then
begin
DMsg.Msg:=Msg.message;
DMsg.wParam:=Msg.wParam;
DMsg.lParam:=Msg.lParam;
DMsg.Result:=0;
Dispatch(DMsg);
end;
end;