Search code examples
delphiwinapipostmessage

Delphi: How to Receive a Custom Windows Message from PostMessage?


I have two applications that I need to communicate via PostMessage (SendMessage is ruled out as I need to have the second Application able to output to Excel whilst being called.

So far Application 1 makes a call to Application 2, making sure that it is open, and when it is, App 1 is set to disabled.

When the user is finished with Application 2 I need to send a message back to Applciation 1 to allow it to unlock.

I have registered the same Windows Message in each application using:

const
  MyMessage = 'My-Message';

var
  MyMessageID: cardinal;

procedure TMF.FormCreate(Sender: TObject);
begin
  MyMessageID := RegisterWindowMessage(MyMessage);
end;

And in Application 2 I can Post the message to Application 1 using:

targetHandle := FindWindow(Pchar('TMF'), Pchar('Send Test'));
...
if PostMessage(targetHandle, (MyMessageID), 0, 0) then
...

What I don't understand is how I declare the Handler for the Message in Application 1.

If I was using a standard Windows Message, such as WM_COPYDATA I'd declare a procedure

procedure WMCopyData(var Msg: TWMCopyData); message WM_COPYDATA;

But that falls down because I can't declare MyMessageID early enough.

Perhaps it's because it's Friday afternoon, but what am I missing?


Solution

  • You cannot use the message keyword because the message constant is not known at compile time. Instead you have to override WndProc:

    procedure WndProc(var Message: TMessage); override;
    ....
    procedure TMF.WndProc(var Message: TMessage);
    begin
      inherited;
      if Message.Msg = MyMessageID then begin 
        ....
      end;
    end;