Search code examples
delphipostmessage

Posted custom messages are never received by my form


I'm using PostMessage to send messages from another unit to the main form, like this:

procedure notify(var Message: TMessage); message 1;

In the procedure, information is shown according to WParam:

procedure TForm1.notify(var Message: TMessage);
begin
  Case (Message.WParam) of
    1: memo1.Lines.Add('task started');
    2: memo1.Lines.Add('in progress');
  end;
end;

In the other unit I send messages like this:

PostMessage(Handle, 1, 2, variable_info);

First of all, what is message ID? I replaced it by 1 because its type is cardinal, what should I use instead? And my messages are never received, because Message.WParam is never equal to 1 or 2. What is wrong in my code?


I edited my code like this: unit1

 const
 WM_MY_MESSAGE = WM_USER + 0;

in the code I added something like this:

 PostMessage(Handle,WM_MY_MESSAGE, 1,value_sent);

TFormUnit:

  private
  procedure notify(var Message :TMessage); message WM_MY_MESSAGE;

  procedure TFormMain.notify(var Message: TMessage);
  begin
  Case (Message.WParam)of // which is 1
   1:
  //------------------------------------------
  begin
   memo1.Lines.Add('task started');

Normally when PostMessage(Handle,WM_MY_MESSAGE, 1,value_sent); is executed I should get the message task started, but it's the same error, nothing happens!


Solution

  • The message ID must be unique. For sending messages within an application, use the constant WM_USER (declared in the Messages unit) as the first valid starting number.

    Values below WM_USER ($0400) are reserved for system-defined messages. From documentation:

    Applications cannot use these values for private messages.

    Declare this in the interface section of your form or in a unit with all other messages in your application.

    const 
      WM_MY_MESSAGE = WM_USER + 0;
    

    Edit:

    In an addition to the question, to get the form window handle in your PostMessage call,

    PostMessage(YourForm.Handle,WM_MY_MESSAGE,1,value_sent);
    

    or

    PostMessage(FindWindow(nil,'YourFormName'),WM_MY_MESSAGE,1,value_sent);