2007. december 6., csütörtök

How to check if the mouse cursor is outside a TForm


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;

Nincsenek megjegyzések:

Megjegyzés küldése