Delphi中子线程向主线程发送消息的方法

思路:在创建子线程的时候将主线程的句柄传送子线程,在子线程发送消息的地方用PostMessage或者SendMessage发送所需要的消息,主线程中自己处理消息循环。代码如下:

主线程:

unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, Unit2;

type
TForm1 = class(TForm)
  lst1: TListBox;
  btn1: TButton;
  btn2: TButton;
  procedure FormCreate(Sender: TObject);
  procedure btn1Click(Sender: TObject);
  procedure btn2Click(Sender: TObject);


  private
    myThread : TMyThread;
    procedure WndProc(var Msg: TMessage); override;
  { Private declarations }

 

  public
  { Public declarations }

end;

var
Form1: TForm1;

implementation

{$R *.dfm}

const USER_MSG = WM_USER + 100;

procedure TForm1.FormCreate(Sender: TObject);
begin
  myThread:=TMyThread.MyCreate(Handle,True);
end;

procedure TForm1.WndProc(var Msg: TMessage);
begin
  if Msg.Msg=USER_MSG then
  begin
    lst1.Items.Add('msg rev');
  end
  else
  begin
    inherited;
  end;
end;

procedure TForm1.btn1Click(Sender: TObject);
begin
  myThread.Resume;
end;

procedure TForm1.btn2Click(Sender: TObject);
begin
  myThread.Suspend;
end;

end.

 

子线程

unit Unit2;

interface

uses
Classes,Messages,Windows;

type
  TMyThread = class(TThread)

  private
    FHandle:THandle;
  { Private declarations }

  protected
    procedure Execute; override;

  public
    constructor MyCreate(AHandle: THandle; CreateSuspended: Boolean);
  end;

implementation

uses unit1;

{ TMyThread }

procedure TMyThread.Execute;
var
  msg:TMessage;
begin
  { Place thread code here }
  msg.Msg := WM_USER+100;
  while (Terminated<>True) do
  begin
    SendMessage(FHandle,msg.Msg,0,0);
    Sleep(500);
  end;
end;


constructor TMyThread.MyCreate(AHandle: THandle; CreateSuspended: Boolean);
begin
  FHandle:= AHandle;
  inherited Create(CreateSuspended);
end;

end.

你可能感兴趣的:(Delphi)