Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi - How do I send a windows message to TDataModule?

I need to send a windows message to a TDataModule in my Delphi 2010 app.

I would like to use

PostMessage(???.Handle, UM_LOG_ON_OFF, 0,0);

Question:

The TDataModule does not have a Handle. How can I send a windows message to it?

like image 226
Charles Faiga Avatar asked Aug 23 '10 20:08

Charles Faiga


2 Answers

You can give it a handle easily enough. Take a look at AllocateHWND in the Classes unit. Call this to create a handle for your data module, and define a simple message handler that will process UM_LOG_ON_OFF.

like image 86
Mason Wheeler Avatar answered Oct 01 '22 14:10

Mason Wheeler


Here is an example demonstrating how to create a TDataModule's descendant with an Handle

uses
  Windows, Winapi.Messages,
  System.SysUtils, System.Classes;

const
  UM_TEST = WM_USER + 1;

type
  TMyDataModule = class(TDataModule)
  private
    FHandle: HWND;
  protected
    procedure   WndProc(var Message: TMessage); virtual;
  public
    constructor Create(AOwner : TComponent); override;
    destructor  Destroy(); override;
    property    Handle : HWND read FHandle;
  end;

...

uses
  Vcl.Dialogs;

constructor TMyDataModule.Create(AOwner : TComponent);
begin
  inherited;

  FHandle := AllocateHWND(WndProc);
end;

destructor  TMyDataModule.Destroy();
begin
  DeallocateHWND(FHandle);

  inherited;
end;

procedure   TMyDataModule.WndProc(var Message: TMessage);
begin
  if(Message.Msg = UM_TEST) then
  begin
    ShowMessage('Test');
  end;
end;

Then we can send messages to the datamodule, like this:

procedure TForm1.Button1Click(Sender: TObject);
begin
  PostMessage(MyDataModule.Handle, uMyDataModule.UM_TEST, 0, 0);
end;
like image 27
Fabrizio Avatar answered Oct 01 '22 15:10

Fabrizio