How do I get the coordinates of the mouse when a control is clicked?

后端 未结 4 1447
遥遥无期
遥遥无期 2021-01-01 23:15

In a TImage\'s OnClick event, I would like to extract the x,y coordinates of the mouse. I would prefer them in relation to the image, but in relation to the form or window i

4条回答
  •  时光说笑
    2021-01-01 23:32

    Mouse.CursorPos contains the TPoint, which in turn contains the X and Y position. This value is in global coordinates, so you can translate to your form by using the ScreenToClient routine which will translate screen coordinates to window coordinates.

    According to the Delphi help file, Windows.GetCursorPos can fail, Mouse.CursorPos wraps this to raise an EOsException if it fails.

    var
      pt : tPoint;
    begin
      pt := Mouse.CursorPos; 
      // now have SCREEN position
      Label1.Caption := 'X = '+IntToStr(pt.x)+', Y = '+IntToStr(pt.y);
      pt := ScreenToClient(pt);
      // now have FORM position
      Label2.Caption := 'X = '+IntToStr(pt.x)+', Y = '+IntToStr(pt.y);
    end;
    

提交回复
热议问题