开发者

Delphi How to get cursor position on a control?

开发者 https://www.devze.com 2023-03-19 03:03 出处:网络
I want to know the position of the cursor on a TCustomControl. How does one go abou开发者_JAVA技巧t finding the coordinates?GetCursorPos can be helpful if you can\'t handle a mouse event:

I want to know the position of the cursor on a TCustomControl. How does one go abou开发者_JAVA技巧t 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消