简体   繁体   中英

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?

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;

You can use MouseMove event:

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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM