Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does clicking a mouse button end up in a WinForms event?

When we click mouse and an a MouseClick event fires in our .NET program, how does the computer know we clicked on the right point in button boundaries?

I mean what is going on under the hood and why don't we need to implement that?

like image 766
Lyrk Avatar asked Oct 15 '15 08:10

Lyrk


People also ask

Which of the following event occurs when the mouse pointer is over the control and mouse button is pressed?

The handler for this event receives an argument of type MouseEventArgs. This event occurs when the mouse pointer is over the control and the user releases a mouse button. The handler for this event receives an argument of type MouseEventArgs.

What is the difference between double click and right click?

Double click is nothing but performing a Left mouse click twice. Right-click is performing a single Right mouse click. This directly interacts with an object.

What is the use of single click?

A single click or "click" is the act of pressing a computer mouse button once without moving the mouse. Single clicking is usually a primary action of the mouse. Single clicking, by default in many operating systems, selects (or highlights) an object while double-clicking executes or opens the object.


1 Answers

Basically that's what the Windows UI framework named User32 does for you. See also MSDN: Windows and Messages.

This framework works by letting your application implement a "message pump" which receives messages from Windows. A message can be "the mouse just moved over this window" or "the mouse button was pressed". Note that a "window" is more than just a "window" in the sense of a form, be sure to read the MSDN link. A button also is a window.

So:

  • A mouse is connected to the PC over a hardware bus
  • User moves the mouse
  • Hardware signals get translated to software signals
  • Windows translates these signals to messages
  • Windows dispatches these messages to the appropriate application's message pump
  • The application does with these messages whatever it wants

Now .NET's WinForms wraps this message pump for you, and exposes messages as events you can subscribe to. You can see it in action by overriding WndProc() on your control of coice:

protected override void WndProc(ref Message m)
{
    Console.WriteLine(m);
    base.WndProc(ref m);
}

More in-depth (from MSDN: About Messages and Message Queues), a Windows message is associated to a window (or "control" in WinForms terms) using a handle. This handle uniquely identifies a control.

This way WinForms knows that a mouse message with handle X is intended for control Y with that handle, so it raises the MouseClick or related event upon receiving that message.

like image 152
CodeCaster Avatar answered Sep 29 '22 23:09

CodeCaster