Changes

Jump to: navigation, search

Understanding C Sharp GUI Events

9,436 bytes added, 19:58, 24 January 2008
New page: <table border="0" cellspacing="0" width="100%"> <tr> <td width="20%">Previous<td align="center">Table of Contents<td width=...
<table border="0" cellspacing="0" width="100%">
<tr>
<td width="20%">[[Designing Forms in Visual Studio|Previous]]<td align="center">[[Visual Basic Essentials|Table of Contents]]<td width="20%" align="right">[[Hiding and Showing Forms in Visual Basic|Next]]</td>
<tr>
<td width="20%">Designing Forms in Visual Studio<td align="center"><td width="20%" align="right">Hiding and Showing Forms in Visual Basic</td>
</table>
<hr>

In the days before graphical environments such as Microsoft windows, applications were developed using a procedural approach. This meant that the path a user would take through an application was dictated by the programmer at the point the application was developed. For example. the application might display a menu listing several options, and prompt the user to select an option. Depending on the user's selection, the application might display a data input screen in which data would need to be entered in the order in which the fields were displayed on the screen. Once the data was entered the user would then be able to press a key to save the data and return to the menu screen again.

The world of the graphical user interface is very different from the old days. Today a user is presented with windows containing multiple controls such as buttons, text fields, toggles and sliders. The mouse allows the user to interact with any of the visible controls in any order they choose. The programmer can, therefore, no longer dictate the path a user will take through an application. A new way of handling the interaction between a user and an application was needed. This approach is known as ''event handling''.

Instead of a procedural approach to programming, applications are now ''event driven''. In essence, the developer defines what the user interface is to look like, and then defines subroutines which will be called when particular events are triggered. For example, the Visual Basic programmer might create a Form containing a number of Buttons. For each Button, the programmer will define the Visual Basic code to be executed when a ''Click'' event is triggered on each button. When the application runs, an ''event loop'' sits in the background and waits for an event to be triggered in the application. Once an event is triggered (such as button click or a a keystroke in a text field) the event loop looks at the object from which the event was triggered to see if an event handler has been defined by the developer for that particular event type. If a handler has been defined, that subroutine is executed and the event loop continues to loop waiting for the next event to be triggered.

== Event Triggers ==

There are a number of ways events can be triggered:

* User Interaction - One of the most common ways for events to be triggered is through user interaction with controls in a Form. Each control has a number of events which can be triggered. For example, a text field can trigger an event when a user types a character or when a user moves the mouse over the control.

* Object Event Triggering - Objects can trigger their own events. For example, the ''Timer'' object can be configured to trigger its own Timer event after a specified amount of time has elapsed.

* Operating System - The Windows operating system can trigger events which can be handled by the application. For example, Windows will trigger an event when part of a window is obscured by another window. In this situation C# receives an event when the previously obscured window area is re-exposed so that it knows to repaint the area.

* Programmatically triggered events - The event of any object may be triggered by the programmer from within the Visual Basic code. For example, a program may need to simulate the event triggered by a user clicking on a button.

== Wiring Up Events in Visual Studio ==

In this section we will look at the steps involved in configuring events on controls in a Form. Create a new ''Windows Application'' project in Visual Studio called ''CSharpEvents''.

In this example we are going to create a Form containing a TextBox, a Label and a Button. We are then going to set up event handlers such that any text typed into the TextBox will appear in the Label control. We will also wire up an event handler on the Button to close the application when the button is pressed.

The first step is to design the Form. Using the Toolbox (see [[Designing Forms in C Sharp and Visual Studio|Designing Forms in C# and Visual Studio]] for an overview of designing forms) add a TextBox, Label and Button to the Form so that form appears as follows:

[[Image:c_sharp_event_form.jpg]]

Select each control in turn and using the Properties panel change the Name of the controls to ''myButton'', ''myLabel'' and ''textInput'' respectively. The Form design is now complete and we can now begin to connect the events to event handlers.

We will begin by defining an event procedure for the TextBox. To access the ''textInput'' control event procedures simply double click on the TextBox control in the Form. Visual Studio will subsequently display the event procedures for the ''textInput'' control. By default Visual Studio picks the most common event, the ''TextChanged'' event, and creates a stub of the subroutine to be called when that event is triggered by the user.

In our example we want every keystroke performed by the user in the TextBox to be displayed by the Label control. In this case the ''TextChanged'' event is exactly the event we want.

With the ''TextChanged'' event still selected it is time to write the C# code that will be executed when the event is triggered. To do so, we will need to set the ''Text'' property of the ''myLabel'' control to equal the ''Text'' property of the ''textInput'' control. The properties of objects are accessed using what is called dot notation. For example the ''Text'' property of ''myLabel'' is accessed in Visual basic code as follows:

<tt>myLabel.Text</tt>

To modify the event procedure, therefore, the code this this event needs to be modified as follows:

<pre>
private void textInput_TextChanged(object sender, EventArgs e)
{
myLabel.Text = textInput.Text;
}
</pre>

Visual Studio, of course, makes life easy for us when accessing properties of objects. At the point that you type the '.' after ''myLabel'' a drop down list of properties available with this type of object is displayed from which to choose. Either select the ''Text'' property from the list, or continue to type the word ''Text''. Repeat this for the ''textInput'' property

The implementation of the TextChanged event handler for our ''inputText'' control is now complete. Now we need to implement the event procedure for the Button. Return to the form design by clicking on the ''Form1.cs'' tab above the code editing area and double click on the myButton component to access the code behind the button. This time the event we need to catch is the ''Click'' event. Once again, Visual Studio anticipates out needs and takes us to the ''myButton_Click()'' event code.

Modify the event procedure to call ''Close()'' as follows:

<pre>
private void myButton_Click(object sender, EventArgs e)
{
Close();
}
</pre>

Now, when the button is pressed the application will exit.

Finally, build and run the application by pressing the '''F5'' key or clicking on the Debug button in the toolbar (the button displaying the green ''Play'' triangle). The application should compile and run. When you type text into the TextBox the characters should also appear in the label:

[[Image:vb_event_example.jpg]]

Clicking the Button should close the application as specified in the ''Click()'' event procedure.

== Setting Up a C# Timer Event ==

At the beginning of this chapter we mentioned that objects can trigger their own events. So far we have only looked at events triggered by user interaction with the application's user interface. We will now look at configuring the ''Timer'' object to trigger its own events. The first step is to add a ''Timer'' object to our application. First, display the Toolbox if it is not already visible, unfold the ''Components'' section of the Toolbox list and scroll down until you find the ''Timer'' object. To add a ''Timer'' to the application simply double click on it. Because the Timer is not a visible object it appears in a special area beneath the Form as shown in the following figure:

[[Image:c_sharp_timer_object.jpg]]

With the ''Timer'' object selected, use the ''Properties'' panel to change the ''Enabled'' property to ''True'' and the ''Interval'' property to ''10000'' (which will cause the Timer to trigger a ''Tick'' event every 10 seconds). Next double click on the ''Timer'' object to edit the event procedure. The ''Timer'' object has a single event, the ''Tick'' event, which is triggered each time the timer interval elapses. We are going to write code to set the myLabel control to display ''Your time is up'' when the ''Tick'' event triggers:

<pre>
private void timer1_Tick(object sender, EventArgs e)
{
myLabel.Text = "Your time is up";
}
</pre>

Build and run the application and notice that after 10 seconds the label text changes to "Your time is up". Enter some text into the TextBox so that the Label text changes again and wait 10 seconds. Once again, the Timer will trigger the ''Tick'' event and the Label text will change.

Navigation menu