Mirror

Check if the mouse cursor is outside a TForm (Views: 102)

Problem/Question/Abstract:

How can I find out if the cursor is leaving a Delphi form?

Answer:

Solve 1:

Add a handler for the CM_MOUSELEAVE message to the form:

unit Unit1;

interface

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

type
TForm1 = class(TForm)
Memo1: TMemo;
private
{ Private declarations }
procedure CMMouseEnter(var msg: TMessage); message CM_MOUSEENTER;
procedure CMMouseLeave(var msg: TMessage); message CM_MOUSELEAVE;
public
{ Public declarations }
end;

var
Form1: TForm1;

implementation

{$R *.DFM}

procedure TForm1.CMMouseEnter(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Entered ' + Name)
else
memo1.Lines.add('Entered ' + TControl(msg.lparam).Name);
end;

procedure TForm1.CMMouseLeave(var msg: TMessage);
begin
if msg.lparam = 0 then
memo1.Lines.add('Left ' + Name)
else
memo1.Lines.add('Left ' + TControl(msg.lparam).Name);
end;

end.


Solve 2:

Place the following code in your form's OnMouseMove event handler, and you'll see SetCapture/ ReleaseCapture in action (plus its side-effects):

procedure TForm1.FormMouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer);
begin
if (GetCapture < > Handle) then {OnMouseEnter}
begin
Beep;
Caption := 'Hello';
SetCapture(Handle);
end
else if (PtInRect(ClientRect, Point(X, Y))) then {OnMouseOver}
Caption := 'X=' + IntToStr(X) + ':Y=' + IntToStr(Y)
else {OnMouseOut}
begin
Beep;
Caption := 'Goodbye!';
ReleaseCapture;
end;
end;


Solve 3:

You can use a timer (the smaller the interval the more sensitive the program) and in the OnTimer event handler control the mouse position to check if the mouse is inside or outside the form:

procedure TForm1.Timer1Timer(Sender: TObject);
var
pt: TPoint;
begin
GetCursorPos(pt);
if (pt.x < Left) or (pt.x > left + Width) then
Caption := 'Out'
else if (pt.y < Top) or (pt.y > Top + Height) then
Caption := 'Out'
else
Caption := 'In';
end;


<< Back to main page