[英]How to catch coordinates of mouse cursor (IDE Delphi) to invoke Context Menu
當我調用上下文菜單創建新控件時,如何捕獲鼠標 cursor (IDE Delphi) 的坐標?
我想通過上下文菜單在調用上下文菜單的相同坐標處創建一個新組件。
我正在創建自己的組件編輯器來執行此操作,然后我需要鼠標的坐標來在那里創建控件。
我不知道我是否很好地理解了您的問題,但是有一些方法可以捕獲鼠標的 position:
方法 1 - 在屏幕上捕獲鼠標 position :在這里您可以像這樣使用TMouse
class :
var
m: TMouse;
begin
lbl_cordinate_screen.Caption := format('Mouse cordinate on screen: x:%d, y:%d',
[m.CursorPos.X, m.CursorPos.y]);
end;
方法 2 - 在控件上捕獲鼠標 position:在這里您可以使用GetCursorPos
,我聲明了一個名為 cursorCordinate 的cursorCordinate
,它將收到一個控件名稱(我使用名為frm_main
的表單作為給定控件,但它可以是任何其他控件,例如按鈕, label 或其他任何東西),它將返回一個包含給定控件上鼠標 position 的TPoint
值:
//function to capture mouse position on a control
function cursorCordinate(myCtrl: TWinControl): TPoint;
var
mouse_p: TPoint;
begin
GetCursorPos(mouse_p);
ScreenToClient(myCtrl.Handle, mouse_p );
result := mouse_p;
end;
用法示例:
begin
lbl_cordinate_form_1.Caption := format('Mouse cordinate on form: x:%d, y:%d',
[cursorCordinate(frm_main).X, cursorCordinate(frm_main).y]);
end;
方法 3 - 在控件上捕獲鼠標 position 的另一種方法:這里您可以使用控件的OnMouseMove
事件及其X
和Y
參數,只需將代碼塊放在此事件中即可。 我用它在 label ( lbl_cordinate_form_2
) 中的表單 ( frm_main
) 上顯示鼠標 position ,但您可以使用任何其他控件的OnMouseMove
事件:
procedure Tfrm_main.FormMouseMove(Sender: TObject; Shift: TShiftState; X,
Y: Integer);
begin
lbl_cordinate_form_2.Caption := format('Mouse cordinate on form: x:%d, y:%d', [x, y]);
end;
您可以在圖像中看到結果; 第一行是方法 1的結果,第二行是方法 2 ,第三行屬於方法 3 :
通過將此代碼添加到FormContextPopup可以獲得鼠標 position
uses FMX.Forms;
...
...
procedure TForm88.FormContextPopup(Sender: TObject; MousePos: TPoint;
var Handled: Boolean);
begin
Label1.Caption:=FMX.Forms.Screen.MousePos.X.ToString+'
'+FMX.Forms.Screen.MousePos.Y.ToString;
end;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.