Search code examples
lazarusmouseentermouseleave

How to detect MouseEnter and MouseLeave on TPanel-like in Lazarus


I need a way, for Lazarus component (TPanel like), to detect when my component has mouse enter, and mouse leave. Delphi has messages CM_MOUSEENTER for that and I need same for Lazarus.

How can I get the same in Lazarus working for Win/Linux?


Solution

  • The TControl class in Lazarus uses the same CM_MOUSEENTER message mechanism as in Delphi. Those messages don't use the OS' messaging system, but they are injected into the control message handler by the Perform method, so they are actually plaftorm independent.

    However, for component developers and consumers there are dedicated methods, MouseEnter and MouseLeave, whose in default implementation invoke OnMouseEnter and OnMouseLeave events.

    How to consume this notification now depends on the situation in which you are. If you are writing your own TCustomPanel descendant component, you should override the mentioned methods like:

    type
      TMyPanel = class(TCustomPanel)
      protected
        procedure MouseEnter; override;
        procedure MouseLeave; override;
      end;
    
    implementation
    
    procedure TMyPanel.MouseEnter;
    begin
      inherited;
      // do your stuff here
    end;
    
    procedure TMyPanel.MouseLeave;
    begin
      inherited;
      // do your stuff here
    end;
    

    If you are just a consumer of TControl based component which doesn't publish the OnMouseEnter and OnMouseLeave events, then you can use e.g. intercept class to publish those events, or use the above code in the interceptor class, but to suggest you a proper way for this situation requires to know more about the control, since it may e.g. internally break the described mechanism for some reason.