Obtain Position/Button of mouse click on DoubleClick event

五迷三道 提交于 2019-12-19 19:44:32

问题


Is there a method to obtain the (x, y) coordinates of the mouse cursor in a controls DoubleClick event?

As far as I can tell, the position has to be obtained from the global:

Windows.Forms.Cursor.Position.X, Windows.Forms.Cursor.Position.Y

Also, is there a method to obtain which button produced the double click?


回答1:


Control.MousePosition and Control.MouseButtons is what you are looking for. Use Control.PointToClient() and Control.PointToScreen() to convert between screen and control relative coordinates.

See MSDN Control.MouseButtons Property, Control.MousePosition Property, Control.PointToClient Method, and Control.PointToScreen Method for details.


UPDATE

Not to see the wood for the trees... :D See Moose's answer and have a look at the event arguments.

This MSDN article lists which mouse actions trigger which events depending on the control.

UPDATE

I missed Moose's cast so this will not work. You have to use the static Control properties from inside Control.DoubleClick(). Because the button information is encoded as bit field yoou have to test as follows using your desired button.

(Control.MouseButtons & MouseButtons.Left) == MouseButtons.Left



回答2:


Use the MouseDoubleClick event rather than the DoubleClick event. MouseDoubleClick provides MouseEventArgs rather than the plain EventArgs. This goes for "MouseClick" rather than "Click" as well...and all the other events that deal with the mouse.

MouseDoubleClick makes sure the mouse is really there. DoubleClick might be caused be something else and the mouse coordinates may not be useful - MSDN: "DoubleClick events are logically higher-level events of a control. They may be raised by other user actions, such as shortcut key combinations."




回答3:


Note: As danbruc pointed out, this won't work on a UserControl, because e is not a MouseEventArgs. Also note that not all controls will even give you a DoubleClick event - for example, a Button will just send you two Click events.

  private void Form1_DoubleClick(object sender, EventArgs e)
   {
       MouseEventArgs me = e as MouseEventArgs;

       MouseButtons buttonPushed = me.Button;
       int xPos = me.X;
       int yPos = me.Y;
   }

Gets x,y relative to the form..

Also has the left or right button in MouseEventArgs.



来源:https://stackoverflow.com/questions/690904/obtain-position-button-of-mouse-click-on-doubleclick-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!