请问用在主窗口发送一个消息,线程中如何接收到?(150分)

  • 主题发起人 主题发起人 bergstorm
  • 开始时间 开始时间
B

bergstorm

Unregistered / Unconfirmed
GUEST, unregistred user!
例如
const
WM_BCP_MSG=WM_USER+100;
主窗口中如何发送这个消息,
线程中又是如何接收呢?能不能写一个具体的小例子
新手啊 命苦啊……
 
var
a : TQuickSort;
begin
postmessage(a.handle,wm_WM_BCP_MSG,0,0);
end;
 
你的线程要有一个消息循环才能接受
 
张无忌,
能不能用个具体的例子来讲一下呢 谢谢
 
你在线程里面用 AllocateHWnd 创建一个隐藏的窗口,用这个窗口的消息处理函数即可
参见 TTimer 的实现:
constructor TTimer.Create(AOwner: TComponent);
begin
inherited Create(AOwner);
FEnabled := True;
FInterval := 1000;
FWindowHandle := AllocateHWnd(WndProc);
// 向 FWindowHandle 发送消息即可
end;

WndProc 就是自己写的该隐藏窗口的消息处理函数,在这里面处理消息即可
 
beta 你的意思我没弄明白
 
//请看下面代码
//一个memo,一个button
unit Unit1;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ExtCtrls, syncobjs;
const
WM_TEST_MSG = WM_USER+168;
type
// tform1 = class ;
ttestthread = class(tthread)
private
fhwnd:hwnd;
fs:string;
fcount:integer;
procedure wndproc(var msg:tmessage);
procedure addline;
public
destructor destroy;override;
procedure afterconstruction;override;
procedure execute;override;
end;

TForm1 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Timer1: TTimer;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormDestroy(Sender: TObject);
private
{ Private declarations }
fthread:ttestthread;
public
{ Public declarations }
end;

var
Form1: TForm1;
fcs:trtlcriticalsection;
implementation
{$R *.dfm}
procedure ttestthread.addline;
begin
inc(fcount);
fs:=inttostr(fcount)+' times Thread receive msg WM_TEST_MSG !';
Entercriticalsection(fcs) ;
form1.Memo1.Lines.Add(fs);
leavecriticalsection(fcs);
end;

procedure ttestthread.wndproc(var msg:tmessage);
begin
with msgdo
if Msg = WM_TEST_MSG then
begin
addline;
end
else
result := defwindowproc(fhwnd, msg, wparam, lparam);
end;

destructor ttestthread.destroy;
begin
deallocatehwnd(fhwnd);
inherited destroy;
end;

procedure ttestthread.afterconstruction;
begin
inherited afterconstruction;
fhwnd:=allocatehwnd(wndproc);
fs:='Initial string';
fcount:=0;
end;

procedure ttestthread.execute;
begin
end;

procedure TForm1.Button1Click(Sender: TObject);
begin
sendmessage(fthread.fhwnd ,WM_TEST_MSG,0,0);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
fthread:=ttestthread.Create(false);
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
fthread.destroy;
end;

initialization
initializecriticalsection(fcs);
end.
 
多人接受答案了。
 
后退
顶部