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;
}
}
THIS OCCURED
The type or namespace name 'WinForms' does not exist in the namespace 'System' (are you missing an assembly reference?)
WHT SHOULD I DO iT URGENT PLZ HELP
Loading
aliPosted May 4, 2010, 6:24 PM
but when i do following changes to change button text
switch (e.Button)
{
case MouseButtons.Left:
button1.Text = ("X");
break;
case MouseButtons.Right:
button1.Text = ("0");
break;
case MouseButtons.Middle:
break;
default:
break;
}
it works it change the text but when i click on form
i want it to change when i click on button
can u help me one more time
Jaish MathewsPosted May 3, 2010, 6:11 AM
Hi,
MouseEventArgs is defines under "System.Windows.Forms".
But you are already in Form so only need to use like below
private void Form_MouseDown(object sender, MouseEventArgs e)
aliPosted May 3, 2010, 3:13 AM
private void Form_MouseDown(object sender, System.Windows.MouseEventArgs e)
THIS error OCCURED
The type or namespace name'MouseEventArgs ' does not exist in the namespace 'System' (are you missing an assembly reference?)
WHT SHOULD I DO iT URGENT PLZ HELP
Jaish MathewsPosted May 1, 2010, 3:30 PM
The EventHandler declaration should be like below.
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form_MouseDown);
You are using System.WinForms.MouseEventHandler. I never saw any thing like this
aliPosted May 1, 2010, 6:06 AM
plz help me bro its ugrent
Amit ChoudharyPosted May 1, 2010, 1:18 AM
Are you doing it in Console application.?? or in Windows itself?