简体   繁体   中英

How to catch coordinates of mouse cursor (IDE Delphi) to invoke Context Menu

How to catch coordinates of mouse cursor (IDE Delphi) when I invoke Context Menu to create a new control?

I'd like to create a new component via Context Menu at same coordinates where Context Menu was invoked.

I'm creating my own component editor to do this, then I need the coordinates of mouse to create the control there.

I don't know if I understood your question well, but there are some ways to capture position of your mouse:

Method 1 - Capture the mouse position on your screen : Here you can use TMouse class like this:

var
  m: TMouse;
begin
  lbl_cordinate_screen.Caption := format('Mouse cordinate on screen: x:%d, y:%d', 
                                          [m.CursorPos.X, m.CursorPos.y]);
end;

Method 2 - Capture the mouse position on a control: Here you can use GetCursorPos , I declared a function called cursorCordinate , it will receive a control name (I used my form named frm_main as given control but it can be any other control like a button, label or anything else) and it will return a TPoint value containing position of mouse on given control:

//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;

usage example:

begin
  lbl_cordinate_form_1.Caption := format('Mouse cordinate on form: x:%d, y:%d',  
                                          [cursorCordinate(frm_main).X, cursorCordinate(frm_main).y]);
end;

Method 3 - Another way to capture the mouse position on a control: Here you can use control's OnMouseMove event and its X and Y parameters, just place your code block in this event. I used it to show mouse position on my form ( frm_main ) in a label ( lbl_cordinate_form_2 ), but you can use any other control's OnMouseMove event:

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;

You can see the result in image; first line is result of Method 1 , second line for Method 2 and third line belongs to Method 3 :

捕获鼠标位置

By add this cod to FormContextPopup can obtain mouse 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;

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