线程高级话题:关于如何在线程中建立消息循环!!!(100分)

  • 主题发起人 pcexplorer
  • 开始时间
P

pcexplorer

Unregistered / Unconfirmed
GUEST, unregistred user!
如何在线程中建立消息循环?
用PostThreadMessage向线程发送消息
如何才能在线程中处理发来的消息
GetMesssage 和 PeekMessage如何在线程中使用
Help Help Help !!!!!
 
随手写的,不知参数对不对.
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;
 
应该用这个等待信号及消息,可以是信号结束线程,如果是消息继续处理并循环
mask用QS_ALLINPUT
DWORD MsgWaitForMultipleObjects(
DWORD nCount, // number of handles in the object handle array
LPHANDLE pHandles, // pointer to the object-handle array
BOOL fWaitAll, // wait for all or wait for one
DWORD dwMilliseconds, // time-out interval in milliseconds
DWORD dwWakeMask // type of input events to wait for
);
 
在线程中用allocatehwnd(wndproc);创建一个隐含窗口,然后就可以象普通的form那样处理
各种消息了
 
是用MsgWaitForMultipleObjects函数,我在很多个地方都说了,用这个函数来在线程中建立
消息循环了,既然有人说了,呵呵,,我也就免了吧:)
 
响应消息不一定要窗口的 :)
 
顶部