How to know if the mouse has entered the component area #35

If you ever created visual components you probably wanted to know if the mouse is over the component. Well, this is a lot easier than you could imagine using Delphi Help :-) There are two Delphi component messages you need to use: CM_MOUSEENTER and CM_MOUSELEAVE.

type
  TMouseButton = class(TButton)
  protected
    ...
    fMouseOut,
    fMouseOver: TNotifyEvent;
    ...
    procedure CMMouseEnter(var Message: TMessage); message CM_MOUSEENTER;
    procedure CMMouseLeave(var Message: TMessage); message CM_MOUSELEAVE;
  published
    ...
    property OnMouseOut: TNotifyEvent read fMouseOut write fMouseOut;
    property OnMouseOver: TNotifyEvent read fMouseOver write fMouseOver;
  end;
  ...
  // Trigger OnMouseEnter event if any assigned
  procedure TMouseButton.CMMouseEnter(var Message: TMessage);
  begin
    if Assigned(fMouseOver) then
      OnMouseOver(Self);
    Message.Result := 1; // Mark message as taken care of
  end;
  ...
  // Trigger OnMouseLeave event if any assigned
  procedure TMouseButton.CMMouseLeave(var Message: TMessage);
  begin
    if Assigned(fMouseOut) then
      OnMouseOut(Self);
    Message.Result := 1; // Mark message as taken care of
  end;
Author: Unknown
Added: 2007/06/02
Last updated: 2007/06/02