|
||||||
How to Capure Mouse and Key Events with C#Use C# to Control Mouse Clicks and Key PressesEvery C# application consists of components such as button and text boxes. A C# form can respond on all its user's activities such as clicking the mouse and typing data.
The Windows applications created by C# programmer will always do more or less the same job:
And all of that is done by using buttons and text boxes, for example the programmer may produce a C# application that:
The programmer has two ways for their application to be aware of the fact that user activities have been carried out:
In either case the programmer monitors what is happening by using an event handler. Using a C# Event Handler with a MouseWhen a C# programmer adds a button to a form it will not actually do anything. That is, of course, because it will not have any code to run. In order for that to happen the programmer must do two things:
The event handler is added to the button (or any component) very easily: cmdDoCalc.Click += new EventHandler(this.button_click);
Now, if the button “cmdDoCalc” is clicked with the mouse then the function “button_click” will be run. The functions called by the event handler must have the same general format: public void button_click (object Sender, EventArgs e) {
do_sqrt ();
}
In this example the function called simply calls a second one. The result is that a label is updated with the square root of the number entered into a text box: public void do_sqrt () {
lblText.Text = Convert.ToString (
Math.Sqrt( Convert.ToDouble( txtIP1.Text)));
}
In this example the calculation is run only when the button is clicked. However the activities of the form can also be driven by events in other components such as text boxes. Using a C# Event Handler with the KeyboardAn event handler can be added to objects such as text boxes so that the user’s keystrokes can be monitored and acted upon. Here a function is run whenever a key on the keyboard is released: txtIP1.KeyUp += new KeyEventHandler (this.key_do_sqrt);
Like the mouse event handler, the function being called has its own particular format: public void key_do_sqrt (object Sender, KeyEventArgs e) {
do_sqrt ();
}
Now the function will be run whenever the user adds a new character into the text box. SummaryThe programmer captures events in a C# form by using event handlers. The event handlers come in two varieties:
Each event handler can be added to a component on a form and then they call a particular function when the event (such as a mouse click or keyboard key press) occurs. By using these the programmer can control all of the activities in their C# application.
The copyright of the article How to Capure Mouse and Key Events with C# in C Programming is owned by Mark Alexander Bain. Permission to republish How to Capure Mouse and Key Events with C# in print or online must be granted by the author in writing.
|
||||||
|
|
||||||
|
|
||||||