Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain Position/Button of mouse click on DoubleClick event

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?

like image 477
user79755 Avatar asked Mar 27 '09 18:03

user79755


3 Answers

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."

like image 179
user410352 Avatar answered Oct 20 '22 18:10

user410352


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.

like image 10
Moose Avatar answered Oct 20 '22 18:10

Moose


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
like image 6
Daniel Brückner Avatar answered Oct 20 '22 18:10

Daniel Brückner