Delphi How to get cursor position on a control?

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

I want to know the position of the cursor on a TCustomControl.

回答1:

You can use MouseMove event:

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


回答2:

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;


回答3:

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;


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!