Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi How to get cursor position on a control?

I want to know the position of the cursor on a TCustomControl. How does one go about finding the coordinates?

like image 574
Little Helper Avatar asked Jul 11 '11 08:07

Little Helper


3 Answers

GetCursorPos can be helpful if you can't handle a mouse event:

function GetCursorPosForControl(AControl: TWinControl): TPoint;
var 
  P: TPoint; 
begin
  Windows.GetCursorPos(P);
  Windows.ScreenToClient(AControl.Handle, P );
  result := P;
end;
like image 150
splash Avatar answered Sep 22 '22 02:09

splash


You can use MouseMove event:

procedure TCustomControl.MouseMove(Sender: TObject; Shift: TShiftState; X,
  Y: Integer);
begin
  Label1.Caption := IntToStr(x) + ' ' + IntToStr(y);       
end;
like image 43
TheHorse Avatar answered Sep 23 '22 02:09

TheHorse


If you want the cursor position when they click on the control, then use Mouse.CursorPos to get the mouse position, and Control.ScreenToClient to convert this to the position relative to the Control.

procedure TForm1.Memo1MouseDown(Sender: TObject; Button: TMouseButton;
  Shift: TShiftState; X, Y: Integer);
var
  pt: TPoint;
begin
  pt := Mouse.CursorPos;
  pt := Memo1.ScreenToClient(pt);
  Memo1.Lines.Add(Format('x=%d, y=%d', [pt.X, pt.y]));
end;

EDIT:

As various people have pointed out, this is pointless on a mouse down event. However as TCustomControl.OnMouseDown is protected, it may not always be readily available on third-party controls - mind you I would probably not use a control with such a flaw.

A better example might be an OnDblClick event, where no co-ordinate information is given:

procedure TForm1.DodgyControl1DblClick(Sender: TObject);
var
  pt: TPoint;
begin
  pt := Mouse.CursorPos;
  pt := DodgyControl1.ScreenToClient(pt);
  Memo1.Lines.Add(Format('x=%d, y=%d', [pt.X, pt.y]));
end;
like image 25
Gerry Coll Avatar answered Sep 25 '22 02:09

Gerry Coll