Name

Message Directive

Syntax

procedure Name(var Msg); message Constant;

Description

A method can be a message handler when you use the message directive. A message handler must take one var argument; usually this argument is of type TMessage or one of the similar types in the Messages unit. The only requirement Delphi imposes is that the message argument be at least as big as a Word. Delphi checks the first Word of the message parameter to decide which message handler to call.

The message handler must specify a constant message number. The message number is stored in the class’s RTTI.

Tips and Tricks

  • Message handlers and dynamic methods are stored in the same RTTI table. Delphi assigns small negative numbers to dynamic methods. To avoid conflicts with dynamic methods, do not use message handler numbers with the most significant bit set, that is, use numbers under $8000 (32,768).

  • Any class—not just controls and components—can define message handlers. Visual controls map Windows messages to Delphi messages, and the Dispatch method of TObject calls the appropriate message handler. In the past, messages were necessary to implement cross-type polymorphism, where objects could respond to a message regardless of base class. Interfaces have replaced this mechanism, so the only need for message handlers in new code is to handle Windows messages.

  • Delphi defines many messages in its Controls unit. Anyone writing new controls or components should be aware of these messages and decide which ones a ...

Get Delphi in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.