Delphi How to get cursor position on a control?

I want to know the cursor position on TCustomControl. How to find the coordinates?

+4
source share
3 answers

You can use the MouseMove event:

procedure TCustomControl.MouseMove(Sender: TObject; Shift: TShiftState; X, Y: Integer); begin Label1.Caption := IntToStr(x) + ' ' + IntToStr(y); end; 
+6
source

GetCursorPos may be useful if you cannot handle the mouse event:

 function GetCursorPosForControl(AControl: TWinControl): TPoint; var P: TPoint; begin Windows.GetCursorPos(P); Windows.ScreenToClient(AControl.Handle, P ); result := P; end; 
+13
source

If you want the cursor position to be pressed on the control, use Mouse.CursorPos to get the position of the mouse, and Control.ScreenToClient to convert it to a 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 noted, this is pointless at a mouse event. However, since TCustomControl.OnMouseDown is protected, it may not always be available on third-party controls - remember that I probably would not use a control with such a drawback.

A better example would be the OnDblClick event, where coordinate information is not specified:

 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; 
+4
source

All Articles