在线程中如何接收通过PostThreadMessage()发送的消息?

dudo 2002-02-22 09:41:59
最好有实例!
...全文
352 点赞 收藏 4
写回复
4 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
dudo 2002-02-23
我试过了,使用消息机制比不是用消息机制,速度差了很多,看来
想他法,感谢各位
回复
torble 2002-02-22
到处收集,呵呵~
回复
stiwin 2002-02-22
请问torble(阿裕)你在什么地下了这什么多的例子
回复
torble 2002-02-22
// 用 PeekMessage 接收

// 一个例子

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.
回复
相关推荐
发帖
非技术区
创建于2007-08-02

799

社区成员

Delphi 非技术区
申请成为版主
帖子事件
创建了帖子
2002-02-22 09:41
社区公告
暂无公告