请问PeekMessage的用法(100分)

S

Since

Unregistered / Unconfirmed
GUEST, unregistred user!
问一个肤浅的问题
如何用PeekMessage和PostThreadMessage在线程中处理消息?
PeekMessage的第一个参数 @msg 如何定义和设置?
请给出详细例程
Thank you!
 
PeekMessage就有像 GetMessage,用来取得消息;
而PostThreadMessage是用来发送消息的。
具体的参数定义、用法参考 Help吧。

PeekMessage的第一个参数 @Msg ,在Delphi里是 TMsg,
你可以这样定义: var MyMsg : TMsg;

下面的代码我瞎写的,请大家指正:
////////////////// main.pas //////////////
unit main;
interface
uses
Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
StdCtrls,MyThread;
const
WM_MyMessage=WM_USER+100;
type
TForm1 = class(TForm)
BtnQuitThread: TButton;
ListBox1: TListBox;
BtnPost: TButton;
BtnStart: TButton;
BtnExit: TButton;
procedure BtnQuitThreadClick(Sender: TObject);
procedure BtnStartClick(Sender: TObject);
procedure BtnPostClick(Sender: TObject);
procedure BtnExitClick(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
MyThread : MsgThread;
end;

var
Form1: TForm1;
implementation
{$R *.DFM}
procedure TForm1.BtnQuitThreadClick(Sender: TObject);
begin
// MyThread.Terminate;
if MyThread = nil then
exit;
if PostThreadMessage(MyThread.ThreadID,
WM_QUIT,0,0) then
Caption := 'Post Message Ok!'
else
Caption := 'Post Message Fail!';
end;

procedure TForm1.BtnStartClick(Sender: TObject);
begin
if (MyThread = nil) then
MyThread := MsgThread.Create(false);
end;

procedure TForm1.BtnPostClick(Sender: TObject);
begin
if MyThread = nil then
exit;
if PostThreadMessage(MyThread.ThreadID,
WM_MyMessage,0,0) then
Caption := 'Post Message Ok!'
else
Caption := 'Post Message Fail!';
end;

procedure TForm1.BtnExitClick(Sender: TObject);
begin
MyThread.Free;
Close;
end;

end.

///////////// MyThread.pas/////////////////
unit MyThread;
interface
uses
Classes,windows, Messages;
const
WM_MyMessage=WM_USER+100;
type
MsgThread = class(TThread)
private
{ Private declarations }
FMyString : string;
protected
procedure Execute;
override;
procedure ShowString;
end;

implementation
{ Important: Methods and properties of objects in VCL can only be used in a
method called using Synchronize, for example,
Synchronize(UpdateCaption);
and UpdateCaption could look like,
procedure PMessage.UpdateCaption;
begin
Form1.Caption := 'Updated in a thread';
end;
}
{ PMessage }
uses Main;
procedure MsgThread.Execute;
var Msg : TMsg;
begin
{ Place thread code here }
FMyString := 'Thread Start!';
Synchronize(ShowString);
while (not Terminated)do
begin
if PeekMessage(Msg,0,0,0,PM_REMOVE) then
begin
if (Msg.message = WM_QUIT) then
begin
FMyString := 'Thread Quit';
Synchronize(ShowString);
Terminate;
end;
if (Msg.message = WM_MyMessage) then
begin
FMyString := 'Thread Get a USER Message!';
Synchronize(ShowString);
end;
end;
end;
end;

procedure MsgThread.ShowString;
begin
Form1.ListBox1.Items.Add(FMyString);
end;

end.
 
admire lha,
但是还有一个问题就是字符串是否可以变成消息传递过去?
sleepEx是不是也可以传递消息?

 
sorry,这两个问题我不太清楚。
干嘛要传字符串? 有消息传过去,根据消息再去处理字符串 不行吗?
 
接受答案了.
 
顶部