ProblemYou want to develop a Windows Forms application that converts between the Fahrenheit, Celsius, and kelvin temperature systems. SolutionSample code folder: Chapter 01\Forms Version Create a Windows Forms application, and add the appropriate controls and logic. DiscussionStart Visual Studio 2005, and then create a new project. The Start Page includes a link to do this, or you can use the File New Project menu command. The New Project dialog appears, as shown in Figure 1-1. Figure 1-1. Visual Studio's New Project dialogEach template listed in this dialog starts with the most basic and empty Visual Basic project and adds just enough source code and configuration settings to get you started on the selected application type. You could choose the Blank Solution template and work your way up to the functionality provided through the Windows Application template, but that's more than we need to accomplish right now. Select Visual Basic (or the Windows entry under Visual Basic) in the "Project types" field and Windows Application in the Templates field, enter the name of your project in the Name field (let's call ours "FormConvertTemp"), and click the OK button. As Visual Studio works behind the scenes to configure the initial project features, let's take a few minutes to review some high school science. The three temperature systems in this programFahrenheit, Celsius, and kelvinare often used to measure heat in the various scientific disciplines:
The ability to convert between the different systems is important, not only for international relations, but also for health considerations ("Mom, I'm too sick to go to school today; I have a temperature of 310.15K!"). By now, Visual Studio should have completed its work and presented you with the initial project form (Figure 1-2). Figure 1-2. Your project's initial formThe form you see represents the initial main form of your application. It is part of a project, a collection of files usually tied to a single target, such as an application, a dynamic-link library, or some other output. In Windows Forms projects, the target is an executable file (with an EXE file extension) that contains a compiled .NET application. All of the files in your project are listed in the Solution Explorer, one of the standard tool windows in Visual Studio (Figure 1-3). The top edge of the Solution Explorer includes a set of toolbar buttons that help you "explore the solution." The most interesting of these buttons is the second from left, the Show All Files button. Clicking this button toggles the view of files included in your project. Most of the files included in your application are hidden from view by default. Visual Studio does an amazing amount of work behind the scenes, and most of this work is stored in hidden project files. Most of these files contain code automatically generated by Visual Studio as you design your program. A few of these files, such as ApplicationEvents.vb, do contain code that you can update manually, but most of your development time will focus on the files that are always displayed. Figure 1-3. The Visual Studio Solution ExplorerThe main area of the form is its design surface, on which you place (or "draw") controls. The Toolbox (Figure 1-4) contains the controls that you can add to your form; it's just one of the many "tool windows" available within Visual Studio. If it's not already displayed, open the Toolbox now through the View Toolbox menu command. Figure 1-4. Partial view of the Visual Studio ToolboxThe selection of controls included in the Toolbox varies based on the active project and window. Beyond the default controls, several third parties offer enhanced controls for use in your projects. Once installed, these controls also appear in the Toolbox. Each form or control has a default configuration, as determined by the developer of the control. You can alter this configuration by changing the active form's or control's properties through the Properties window (Figure 1-5). If it is not already in view, display the Properties window with the View Properties Window menu command. Figure 1-5. Partial view of the Properties windowThe properties for the active item are pretty easy to adjust: select the form or control you want to modify, select a property in the Properties window based on the property name in the left column, and use the mouse or keyboard to modify its value in the right column. Some properties can be expanded into distinct sub-properties using the plus sign (+) to the left of the property name. And while most properties accept simple text values, others have mouse-friendly drop-down editors. Before adding controls to our form, let's configure the properties of the form itself. Using the Properties window, set the form's properties as shown in Table 1-1. This table lists only those properties that deviate from their default settings.
Now let's add the controls to the form. This project will use seven controls:
Use the Toolbox to select and add controls to the form. Add a control either by double-clicking on the control in the Toolbox or by selecting the control in the Toolbox and then "drawing" it on the surface of the form using the mouse. Go ahead and add the three RadioButton controls, three TextBox controls, and one Button control, and arrange them so that your form resembles Figure 1-6. You may also want to resize the form to visually fit the contained controls. Figure 1-6. Project form with included controlsSome of the properties in these controls also need to be adjusted. Use the values in Table 1-2 to guide you through the property updates.
The "&" character added to some of the properties sets the keyboard shortcut for that control so that the user can activate it with the Alt+key keyboard sequence. There are two more tasks to perform on the form itself before we start writing code, both destined to make the form easier to use. The first is to allow the Enter or Return key to act like a click on the ConvertTemperature button. This is done by setting one of the form's properties: AcceptButton. Setting this property to the name of a valid controlin this case, the ConvertTemperature button controlenables this keyboard action. Go ahead and set the form's AcceptButton property now. The second user-friendly update involves setting the " tab order" of the controls on the form. The Tab key allows the user to move from one form control to another, but the movement may look somewhat random to the user unless you specifically declare the order. To set the tab order, first make sure that the formand not one of its contained controlsis the active object in the designer window. Then select the View Tab Order menu command. A small number appears next to each control. To readjust the tab order, click the controls in the order you want them to appear (Figure 1-7). You can also set the tab order by altering the TabIndex property of each control, but the mouse method is generally quicker. Figure 1-7. Project form with tab order set for each controlWhen you are finished, select the View Tab Order menu command once more (or press the Escape key) to return to standard editing. Now it's time to program! All of the code for this application will appear in the ConvertTemperature button's Click event procedure, which you can access by double-clicking on the ConvertTemperature button itself. Visual Studio switches to a code editor with the following event procedure template ready to use: Public Class ConvertForm Private Sub ConvertTemperature_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles ConvertTemperature.Click End Sub End Class Add the following code to the Click event procedure body. It determines the source temperature type, checks for valid input, and then performs the conversion: ' ----- Convert between Fahrenheit, Celsius, and kelvin. On Error Resume Next If (SourceFahrenheit.Checked = True) Then ' ----- Convert from Fahrenheit to other types. If (IsNumeric(ValueFahrenheit.Text) = True) Then ' ----- F->C, F->K. ValueCelsius.Text = _ (Val(ValueFahrenheit.Text) - 32) / 1.8 ValueKelvin.Text = _ ((Val(ValueFahrenheit.Text) - 32) / 1.8) + 273.15 Else ' ----- Invalid data. ValueCelsius.Text = "Error" ValueKelvin.Text = "Error" End If ElseIf (SourceCelsius.Checked = True) Then ' ----- Convert from Celsius to other types. If (IsNumeric(ValueCelsius.Text) = True) Then ' ----- C->F, C->K. ValueFahrenheit.Text = _ (Val(ValueCelsius.Text) * 1.8) + 32 ValueKelvin.Text = Val(ValueCelsius.Text) + 273.15 Else ' ----- Invalid data. ValueFahrenheit.Text = "Error" ValueKelvin.Text = "Error" End If Else ' ----- Convert from kelvin to other types. If (IsNumeric(ValueKelvin.Text) = True) Then ' ----- K->F, K->C. ValueFahrenheit.Text = _ ((Val(ValueKelvin.Text) - 273.15) * 1.8) + 32 ValueCelsius.Text = Val(ValueKelvin.Text) - 273.15 Else ' ----- Invalid data. ValueFahrenheit.Text = "Error" ValueCelsius.Text = "Error" End If End If The program is now ready to use in all weather conditions. Although this program is pure .NET through and through, the only .NET code we witnessed was through the event handler. The call to the ConvertTemperature_ Click event happens indirectly in the code; there is no line of source code, at least in your code, that makes a direct call to the event handler. When the user clicks on the ConvertTemperature button, the low-level device driver for the mouse inserts mouse-down and mouse-up events into the global Windows input-processing queue. The device driver doesn't know anything about the various windows displayed on-screen or about .NET; it reports only that a mouse event occurred at a specific X and Y position on the screen. The Windows operating system uses this location to determine which window or control was clicked. Once that's determined, it sends relevant messages to the message queue of the application that owns the clicked window. The application notifies the clicked control that the user has, in fact, clicked that control. Finally, the code within the .NET control issues a RaiseEvent statement, which triggers a call to the ConvertTemperature_Click event handler. That's a lot of steps between your finger and the event handler. Fortunately, you don't have to handle all of those steps yourself. The relevant logic already exists in Windows and in .NET; you just have to write the event handler and connect it to the specific event through the handler's Handles keyword (which Visual Basic 2005generates for you): Private Sub ConvertTemperature_Click( _ ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles ConvertTemperature.Click The rest of the code in the application is composed of standard logic and calculations that you might find in code from any programming language: If conditional statements, assignment statements, and expression processing with operators such as the multiplication operator (*). See AlsoThe other recipes in this chapter demonstrate how to implement the same program, using different types of interfaces. |