首页  编辑  

在线程中响应消息

Tags: /超级猛料/Thread.线程/   Date Created:

在线程中响应消息

type

 TMyThread=class(TThread)

 private

    FOwner:TControl;

    FOwnerProc:TWndMethod;

    FMessage:TMessage;

    FEvent  :TSimpleEvent;

    procedure ThreadWndProc(var Message:TMessage);

    constructor Create(AOwner:TControl);

    destructor Destroy;

 protect

    procedure Execute;override;

 end;    

constructor TMyThread.Create(AOwner:TControl);

begin

 inherited Create(True);

 FOwner:=AOwner;

 if Assigned(FOwner) then

 begin

      FOwenrProc:=AOwner.WindowProc;

      FOwner.WindowProc:=ThreadWndProc;

 end;

 FEvent:=TSimpleEvent.Create;

end;

destroy TMyThread.Destroy;

begin

    if Assigned(FOwner) then

       FOwner.WindowProc:=FOwnerProc;    

    FEvent.Free;

    inherited Destroy;

end;

procedure TMyThread.ThreadWndProc(var Message:TMessage);

begin

   if Message.Msg=WM_DESTROY then    

   begin

        FOwner.WindowProc:=FOwnerProc;

        FOwnerProc:=nil;

        FOwner:=nil;

   end;

   if Message.Msg= 所要处理的消息 then

   begin

        FMessage:=Message;

        FEvent.SetEvent;

   end

   else if Assigned(FOwnerProc) then FOwnerProc(Message);      

end;

procedure TMyThread.Execute;

begin

  while not Terminated do

  begin

       FEvent.WaitFor(INIFILE);

       FEvent.ResetEvent;

      ....//根据FMessage处理消息

  end

end;