Search:

Custom Search
_________________________________________________________________

Monday, May 19, 2008

MouseDown Event in C#.

The MouseDown event is the one I personally use every time a control needs both events for left and right click (middle click is also supported).
So lest say we want to add the mouseDown event to a Button control somewhere in a windows form. So you can go ahead and add this event.

This header shows appear in the form:

private void button2_MouseDown(object sender, MouseEventArgs e)

So lets proceed to add some code here.
The way to see which button has been clicked is by using a switch statement:

switch (e.Button)
{

case MouseButtons.Left:

//Place here event for left click

break;

case MouseButtons.Right:

//Place here event for right click

break;

default:

break;

}

Great, now your application can distinguish between lest and right click.
To make sure this works, you can add a messageBox saying what event should run.

Complete Code:

private void button2_MouseDown(object sender, MouseEventArgs e)
{

switch (e.Button)
{

case MouseButtons.Left:

MessageBox.Show(this, "Left Button Click");

break;

case MouseButtons.Right:

MessageBox.Show(this, "Right Button Click");

break;

default:

break;

}
}

No comments: