Using Delphi's message keyword handler syntax with variable constants?

As David states in his answer, message ID's in declarative message handlers are required to be constant expressions, so there is no way to implement a handler for a variable message number in this way.

However, you still do not need to sub-class every window to be able to respond to such messages. Or rather, you do not need to perform any further sub-classing than you are already doing by declaring a form or control class.

You can handle your custom, registered message by over-riding the virtual WndProc method. You won't be able to use a select .. case statement to handle the message since this similarly requires constant expressions for the matching cases, but you can use a simple if .. then statement to catch your message, calling inherited for everything else:

procedure TMyForm.WndProc(var aMessage: TMessage);
begin
  if aMessage.Msg = WM_GrobFrobber then
  begin
    { Handle the message or pass to a WMGrobFrabber() method 
      with suitably repacked and typed params, as required/desired }
  end
  else
    inherited WndProc(aMessage);
end;

You could introduce a virtual WMGrobFrabber in a form class which you then use consistently as the base class for all forms in your application(s), so that you can simply override that method to handle this message, rather than having to regurgitate the WndProc conditional handler code every time.

This doesn't solve all your problems. It doesn't provide a way to use the declarative message handler syntax, but it is still quite elegant (imho).

If such messages are used exclusively for responding to broadcast messages (which I believe is the only circumstance in which you need be concerned about message id's conflicting with those used by others) then you could create a non-visual component that implements a message handler specifically to respond to this message by firing an event with a published event handler. Then you don't need to sub-class at all to implement a response to such broadcasts on a form, just drop a handler component on the form and implement a handler for the component's event.

That is obviously more complicated than would be appropriate to deal with in an answer to this question, but might be worth considering.


The message ID associated with a message method must be a constant expression.

Tags:

Delphi