Receive Windows Messages In NonWindowed Control

View Code
interface

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

type

  TMsgReceiver = class(TObject)
  private
    fMsgHandlerHWND : HWND;

    WM_MY_UNIQUE_MESSAGE : Cardinal;

    procedure WndMethod(var Msg: TMessage);
  public
    Point : TPoint;

    constructor Create;
    destructor Destroy; override;
  end;

  TClickSendForm = class(TForm)
    procedure FormCreate(Sender: TObject);
    procedure FormMouseDown(Sender: TObject; Button: TMouseButton;  Shift: TShiftState; X, Y: Integer);
    procedure FormDestroy(Sender: TObject);
  private
    WM_MY_UNIQUE_MESSAGE : Cardinal;
    fMsgReceiver: TMsgReceiver;
    function GetMsgReceiver: TMsgReceiver;
    property MsgReceiver : TMsgReceiver read GetMsgReceiver;
  public
    { Public declarations }
  end;

var
  ClickSendForm: TClickSendForm;

implementation

{$R *.dfm}

procedure TClickSendForm.FormCreate(Sender: TObject);
begin

  //instantiate MsgReceiver
  MsgReceiver;

  WM_MY_UNIQUE_MESSAGE := RegisterWindowMessage('MSG_MY_UNIQUE_MESSAGE');
end;

{ TMsgReceiver }

constructor TMsgReceiver.Create;
begin
  inherited Create;

  fMsgHandlerHWND := AllocateHWnd(WndMethod);

  WM_MY_UNIQUE_MESSAGE := RegisterWindowMessage('MSG_MY_UNIQUE_MESSAGE');

end;

destructor TMsgReceiver.Destroy;
begin
  DeallocateHWnd(fMsgHandlerHWND);
  inherited;
end;

procedure TMsgReceiver.WndMethod(var Msg: TMessage);
begin
  if Msg.Msg = WM_MY_UNIQUE_MESSAGE then
  begin
    Point.X := Msg.LParam;
    Point.Y := Msg.WParam;

    //just to receive some "output"
    Windows.Beep(Point.X, Point.Y);
  end
  else
    Msg.Result := DefWindowProc(fMsgHandlerHWND, Msg.Msg, Msg.wParam, Msg.lParam);
end;

procedure TClickSendForm.FormDestroy(Sender: TObject);
begin
  FreeAndNil(fMsgReceiver);
end;

procedure TClickSendForm.FormMouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Integer);
begin
  PostMessage(HWND_BROADCAST, WM_MY_UNIQUE_MESSAGE, x, y);
end;

function TClickSendForm.GetMsgReceiver: TMsgReceiver;
begin
  if fMsgReceiver = nil then fMsgReceiver := TMsgReceiver.Create;
  result := fMsgReceiver;
end;

end.

转载于:https://www.cnblogs.com/Jekhn/archive/2012/04/21/2461508.html

你可能感兴趣的:(Receive Windows Messages In NonWindowed Control)