DelphiFAQ Home Search:

Catching ALL mouse events

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

Question:

I tried to override the MouseDown() method in a subclass of TForm to get every event for a general handler.

I get only the events, when the user clicks somewhere on the form, where it has no controls. When the user clicks on a control, the message is handled by this control.

How can I get every MouseDown event in a form?


Answer:

The Application.OnMessage event will see all mouse messages before they are delivered to the control under the mouse. You work at the API level there, however. If none of the controls needs to do special mouse processing just hook the same event to all OnMouse* events of interest.
The Sender parameter will tell you which control fired the handler.

Start with the example below:

unit Unit1;

interface

uses
  Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs,
  StdCtrls;

type
  TForm1 = class(TForm)
    ListBox1: TListBox;
    procedure FormCreate(Sender: TObject);
  private
    { private declarations }
    procedure MyMouseEvent(var Msg: TMsg; var Handled: Boolean);
  public
    { public declarations }
  end;

var
  Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.MyMouseEvent(var Msg: TMsg; var Handled: Boolean);
var
  s : string;
begin
  case Msg.message of
    wm_LButtonDown: s := 'left mouse down';
    wm_LButtonUp:   s := 'left mouse up';
    wm_MouseMove:   s := 'mouse move';
    else            s := '';
  end;
  if s <> '' then
    ListBox1.Items.Insert(0, s);
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  Application.OnMessage := MyMouseEvent;
end;

end.
You don't like the formatting? Check out SourceCoder then!
Content-type: text/html

Comments:

2012-10-16, 06:34:00
anonymous from South Africa  
thanks, works perfectly!!!
2014-06-11, 04:58:02
from India  

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: