C# Mouse Events

An essential aspect of Windows programming is the use of the mouse.

Bear in mind that the mouse is hardware and not software. Windows will detect what happens with the mouse and generate events as appropriate. It sends an object of type MouseEventArgs (or in some cases EventArgs, the base class) to each handler as its second argument.


Mouse Events

There are several kinds of mouse events: (list from an MSDN page)

As you may gather, EventArgs provides less information for us than MouseEventArgs.


MouseEventArgs Class

This gives us information about what has just happened with the mouse.

There is a constructor, but it does not seem useful.

Properties: (all "get" only)


How do we use this?

Suppose we want to handle MouseDown events. We will need a using statement for System.Windows.Forms.

In the InitializeComponent method, we need a line:

     this.MouseDown += new MouseEventHandler(this.Form_MouseDown);

The event handler might look like this:

     private void Form_MouseDown(object sender, MouseEventArgs e)
     {
      switch (e.Button)
      { 
       case MouseButtons.Left:
           MessageBox.Show("Left Button Click");
           break;
       case MouseButtons.Right:
           MessageBox.Show("Right Button Click");
           break;
       default:
           break;
      }
     }

In the Designer file, we need a line to attach the handler to the event:

this.MouseDown += 
        new System.Windows.Forms.MouseEventHandler(this.Form_MouseClick);