Declaring a New Message-handling Method

From RAD Studio
Jump to: navigation, search

Go Up to Creating New Message Handlers

There are two sets of circumstances that require you to declare new message-handling methods:

  • Your component needs to handle a Windows message that is not already handled by the standard components.
  • You have defined your own message for use by your components.

To declare a message-handling method, do the following:

  1. Declare a procedure method preferably in the protected or private part of the component's class declaration.
  2. Preferably name the method after the message it handles, without any underline characters.
  3. Pass a single var parameter called Message, of type TMessage.
  4. Add the message directive at the end of your procedure's declaration, specifying the code of the message that the method will handle.
  1. If you are using C++, then you also need to create a message mapping immediately after your method's declaration, using the following syntax:

      MESSAGE_HANDLER(msgCode, msgType, msgHandler)

    The msgCode parameter represents the code of the message that the method handles. The msgType parameter represents the type of the method's var parameter, which usually is TMessage as specified in step 3. Finally, the msgHandler paremeter specifies the name of the handler method, which must be the same with the name of your procedure.

  2. Within the message method implementation, write code for any handling specific to the component.

  3. Call the inherited message handler, if you want the event to also be handled by ancestor message-handling methods.

  4. Note: In order to handle more specific messages, the type of the var parameter can also be one of TWMKey, TWMMouse, TWMPaint, TWMMenuChar, TWMNotify, or TWMLButtonDown.

    Note: For a complete list of the codes of all the predefined messages to use with the message directive, see the list of constants in the Messages unit. You can also create a new kind of message, which is discussed in Defining Your Own Messages.

    For more information on declaring a new message-handling method, see the Message Methods section of the Methods (Delphi) page.


Here is the declaration of a message handler for a user-defined message called CM_CHANGECOLOR.

   TMyComponent = class(TControl)
   procedure CMChangeColor(var Message: TMessage); message CM_CHANGECOLOR;
 procedure TMyComponent.CMChangeColor(var Message: TMessage);
   { set color from long parameter }
   Color := Message.lParam;
   { call the inherited message handler }
 #define CM_CHANGECOLOR (WM_APP + 400)
 class TMyControl : public TControl
   void __fastcall CMChangeColor(TMessage &Message);

 void __fastcall TMyControl::CMChangeColor(TMessage &Message)
   // set color from long parameter
   Color = Message.LParam;
   // call the inherited message handler

See Also