随手写的,不知参数对不对.
1:
TMainForm.ButtonCLick;
begin
SetEvent(Thread.Event);
end;
type
TMyThread = class(Thread)
private
FEvent: THandle;
public
property Event: THandle read FEvent;
end;
procedure TMyThread.Execute;
begin
Event := CreateEvent(nil, True, False, nil);
while Truedo
case WaitForSingleObject(Event, INIFITINE) of
WAIT_OBJECT_0:
begin
PostMessage(MainForm.Handle, WM_SETTEXT, 0, Integer(PChar('Thread Exit.')));
break;
end;
end;
CloseHandle(Event);
FreeOnTerminate := True;
end;
2:
//发个消息给线程
TMainForm.ButtonCLick;
begin
PostThreadMessage(MyThread.ThreadID, WM_USER, 0, 0);
end;
//退出WaitFor
TMainForm.ButtonCLick;
begin
SetEvent(MyThread.Event);
end;
//如果使用GetMessage,就不用PeekMessage来创建消息队列,直接使用它来取消息,
//因为PeekMessage如果没有消息马上返回False,而GetMessage是阻塞线程等待消息的到来.
procedure TMyThread.Execute;
var
msg: TMsg;
begin
//建立消息队列
PeekMessage(msg, 0, 0, 0, PM_NOREMOVE);
FEvent := CreateEvent(nil, True, False, nil);
try
while Truedo
case MsgWaitForMultipleObjects(1, FEvent, False, INIFITINE, QS_ALLINPUT) of
WAIT_OBJECT_0:
begin
PostMessage(MainForm.Handle, WM_SETTEXT, 0, Integer(PChar('Thread Exit')));
break;
end;
WAIT_OBJECT_0 + 1:
begin
PostMessage(MainForm.Handle, WM_SETTEXT, 0, Integer(PChar('Recv MainForm Msg')));
while PeekMessage(msg, 0, 0, 0, PM_REMOVE)do
begin
//if msg.msg = ... then
//do you thing
DispatchMessage(msg);
end;
end;
end;
finally
CloseHandle(FEvent);
end;
end;