原文:http://topic.csdn.net/u/20100107/11/161c95f0-eec2-45fc-a433-f50ec725f09e.html
PostMessage与PostThreadMessage的区别
帖子标题应改为PostMessage与PostThreadMessage的区别。消息队列是属于线程的,Post消息就是把消息放到目标线程的消息队列中。这两者的区别在于,PostMessage通过指定目标窗口句柄来确定目标线程,通常情况下由窗口过程来处理消息;PostThreadMessage直接指定线程ID来确定目标线程,没有目标窗口,只能在消息循环中直接根据消息类型做相应的处理。在程序设计的选择方面,如果是UI线程,则应使用PostMessage;如果是工作线程,则应使用PostThreadMessage,不要为了接收消息而创建窗口。
==================线程内的2种消息循环========================
有如下情况:在主线程中创建一个子线程,主线程 通过 发送消息 来通知子线程,我见过有两种方式:
1、子线程中
Delphi(Pascal) code
procedure TThread.WndProc(var Message: TMessage);
begin
DefWindowProc(FWnd, Message.Msg, Message.WParam, Message.LParam);
end;
procedure TThread.Execute;
begin
{$IFDEF DELPHI_6_UP}
FWnd := Classes.AllocateHWnd(WndProc);
{$ELSE}
FWnd := AllocateHWnd(WndProc);
{$ENDIF}
try
while not Terminated do
begin
try
GetMessage(Msg, FWnd, 0, 0);
if //想要自己处理的消息
begin
//相关操作
end
else if not Terminated then
DispatchMessage(Msg);
except
end;
end;
finally
{$IFDEF DELPHI_6_UP}
Classes.DeallocateHWnd(FWnd);
{$ELSE}
DeallocateHWnd(FWnd);
{$ENDIF}
end;
end;
主线程: 用 PostMessgae 通知子线程
2、子线程中:
Delphi(Pascal) code
procedure TThread.Execute;
begin
while not Terminated do
begin
try
GetMessage(Msg, 0, 0, 0);
//根据 不同情况 ,做不同事情
except
end;
end;
end;
主线程:用PostThreadMessage通知子线程
上面两种方式,那种比较好?比较合理,高效,健壮?或有更好的方式?
PostMessage与PostThreadMessage的区别
帖子标题应改为PostMessage与PostThreadMessage的区别。消息队列是属于线程的,Post消息就是把消息放到目标线程的消息队列中。这两者的区别在于,PostMessage通过指定目标窗口句柄来确定目标线程,通常情况下由窗口过程来处理消息;PostThreadMessage直接指定线程ID来确定目标线程,没有目标窗口,只能在消息循环中直接根据消息类型做相应的处理。在程序设计的选择方面,如果是UI线程,则应使用PostMessage;如果是工作线程,则应使用PostThreadMessage,不要为了接收消息而创建窗口。
==================线程内的2种消息循环========================
有如下情况:在主线程中创建一个子线程,主线程 通过 发送消息 来通知子线程,我见过有两种方式:
1、子线程中
Delphi(Pascal) code
procedure TThread.WndProc(var Message: TMessage);
begin
DefWindowProc(FWnd, Message.Msg, Message.WParam, Message.LParam);
end;
procedure TThread.Execute;
begin
{$IFDEF DELPHI_6_UP}
FWnd := Classes.AllocateHWnd(WndProc);
{$ELSE}
FWnd := AllocateHWnd(WndProc);
{$ENDIF}
try
while not Terminated do
begin
try
GetMessage(Msg, FWnd, 0, 0);
if //想要自己处理的消息
begin
//相关操作
end
else if not Terminated then
DispatchMessage(Msg);
except
end;
end;
finally
{$IFDEF DELPHI_6_UP}
Classes.DeallocateHWnd(FWnd);
{$ELSE}
DeallocateHWnd(FWnd);
{$ENDIF}
end;
end;
主线程: 用 PostMessgae 通知子线程
2、子线程中:
Delphi(Pascal) code
procedure TThread.Execute;
begin
while not Terminated do
begin
try
GetMessage(Msg, 0, 0, 0);
//根据 不同情况 ,做不同事情
except
end;
end;
end;
主线程:用PostThreadMessage通知子线程
上面两种方式,那种比较好?比较合理,高效,健壮?或有更好的方式?