您需要做的是在您的线程中设置一个消息循环,并在主线程中使用AllocateHWnd来向后和向前发送消息.这很简单.
在你的线程执行函数中有以下内容:
procedure TMyThread.Execute;
begin
// this sets up the thread message loop
PeekMessage(LMessage, 0, WM_USER, WM_USER, PM_NOREMOVE);
// your main loop
while not terminated do
begin
// look for messages in the threads message queue and process them in turn.
// You can use GetMessage here instead and it will block waiting for messages
// which is good if you don't have anything else to do in your thread.
while PeekMessage(LMessage, 0, WM_USER, $7FFF, PM_REMOVE) do
begin
case LMessage.Msg of
//process the messages
end;
end;
// do other things. There would probably be a wait of some
// kind in here. I'm just putting a Sleep call for brevity
Sleep(500);
end;
end;
Run Code Online (Sandbox Code Playgroud)
要向您的主题发送消息,请执行以下操作:
PostThreadMessage(MyThread.Handle, WM_USER, 0, 0);
Run Code Online (Sandbox Code Playgroud)
在主线程方面,使用AllocateHWnd(在Classes单元中)设置一个窗口句柄,并传递一个WndProc方法.AllocateHWnd非常轻巧,易于使用:
TMyMessageReciever = class
private
FHandle: integer;
procedure WndProc(var Msg: TMessage);
public
constructor Create;
drestructor Destroy; override;
property Handle: integer read FHandle;
end;
implementation
constructor TMyMessageReciever.Create;
begin
inherited Create;
FHandle := Classes.AllocateHWnd(WndProc);
end;
destructor TMyMessageReciever.Destroy;
begin
DeallocateHWnd(FHandle);
inherited Destroy;
end;
procedure TMyMessageReciever.WndProc(var Msg: TMessage);
begin
case Msg.Msg of
//handle your messages here
end;
end;
Run Code Online (Sandbox Code Playgroud)
并使用其中任何一个发送消息SendMessage,这将阻止直到消息已被处理,或者PostMessage异步执行.
希望这可以帮助.
| 归档时间: |
|
| 查看次数: |
1362 次 |
| 最近记录: |