Tools Used : Visual C# .NET
Handling events in C# is little bit tricky than in C++ or VB. In C#, you write a delegate and then write an event handler. These event handlers are overridable public events defined in the Control or other WinForms classes.
1. Write a Delegate
I want to handle Mouse Down events and do something when left or right mouse buttons are pressed. Write this line of code in your InitializeComponent function.
this.MouseDown += new System.WinForms.MouseEventHandler(this.Form_MouseDown);2. Write the Event
Now you write the event handle. The output parameter of your event returns System.WinForms.MouseEventArgs object which gives you the details about mouse down such as what button is pressed or how many times. Here are MouseEventArgs members.
MouseEventArgs members
| Button | Indicates which mouse button was pressed. It could be Left, Right, Middle, or None. |
| Clicks | Indicates the number of times the mouse button was pressed and released. |
| Delta | Indicates a signed count of the number of detents the mouse wheel has rotated. |
| X | The x-coordinate of mouse click. |
| Y | The y-coordinate of mouse click. |
Event Handler
- private void Form_MouseDown(object sender, System.WinForms.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;
- case MouseButtons.Middle:
- break;
- default:
- break;
- }
- }
Then, I need to know where to put THIS!:
- private void Form_MouseDown(object sender, System.WinForms.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;
- case MouseButtons.Middle:
- break;
- default:
- break;
- }
- }
AlanPosted Apr 16, 2008, 2:00 PM
Well, the following line goes in the InitializeComponent() method but, if you're using Visual Studio, you don't need to do this manually - in fact it's better if you don't!
this.MouseDown += new System.WinForms.MouseEventHandler(this.Form_MouseDown);
In the VS designer, click anywhere in the Form and then click on the 'lightning bolt' symbol in the Properties Box to get a list of the form's properties and then double-click on the MouseDown event. This will cause a MouseDown event handler skeleton to be opened up similar to the following:
private
void Form1_MouseDown(object sender, MouseEventArgs e){
}
So just insert the method code from Mahesh's article in there.
If you look at the InitializeComponent() method, which is managed by the VS designer, you'll find that the line I mentioned earlier in this post has been automatically inserted for you so there's nothing more to do there.