Get the point of click on a control

2019-07-17 05:04发布

问题:

I am using an old ActiveX control in my C# Win App. it has a MouseUp event that its eventArgs is passing the X and Y of the point that we have clicked but for my scenario I am using its ItemClick event and its eventArgs does not have the info about X and Y. but I need to know them to show my pop-up... so is there a way I can find out what is the location of X and Y that user has right-clicked so I can pass it to my contextMenuStrip.Show method.

Thanks

回答1:

The Control class has a static readonly MousePosition property, this gives the mouse coordinates on the screen. You could use this to know where to position the ContextMenu.

From MSDN:

Control.MousePosition Property

Type: System.Drawing.Point

A Point that contains the coordinates of the mouse cursor relative to the upper-left corner of the screen.



回答2:

Cursor.Position will get you the current screen coordinates of the cursor. For most uses this is good enough, even though the mouse can potentially move between the click and the handler being called.



回答3:

You need to get the cursor position which gets the screen position, then call pointToClient from within the control to get the relevant point to the control. Aka. 0,0 is the top left of the control.

this.PointToClient(Cursor.Position);

+1 to other answers for leading me in the right direction.