Mega Code Archive

 
Categories / Delphi / Examples
 

Catching all mouse events

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.