Visual Studio .NET and Forms

Team-Fly    

 
Application Development Using Visual Basic and .NET
By Robert J. Oberg, Peter Thorsteinson, Dana L. Wyatt
Table of Contents
Chapter 7.  Windows Forms


Although it is perfectly feasible to create Windows Forms applications using only the command-line tools of the .NET Framework SDK, in practice it is much easier to use Visual Studio .NET. You can get started by creating a Windows Application project, which provides starter code and sets up references to the required .NET libraries. You can then use the Forms Designer to drag and drop controls from a toolbox onto your forms. The Forms Designer inserts all the needed boilerplate code to make your controls work within your forms. There is a Properties window which makes it easy to set properties of your controls at design time. You can also set properties via code at runtime.

The same Forms Designer can be used in all .NET languages. A similar designer is available for visually drawing Web Forms, which we will discuss in Chapter 14 on ASP.NET.

Windows Forms Demonstration

To become acquainted with using Visual Studio .NET to create Windows applications, we will recreate the ByHand example shown previously. Because this process is interactive, it is outlined below in numbered steps:

  1. graphics/codeexample.gif

    Using Visual Studio .NET, create a VB.NET project named Greeting that is a Windows Application in the Demos folder. See Figure 7-10. (The completed solution is found in the Greeting folder.).

    Figure 7-10. Creating a new Windows Application project.

    graphics/07fig10.jpg

  2. Open the Toolbox by dragging the mouse over the vertical Toolbox tab on the left side of the main Visual Studio window. If the Toolbox tab does not show, you can open it using the menu View Toolbox. You can make the Toolbox stay open by pushing the "push-pin" next to the X on the title bar of the Toolbox. (The little yellow box will say "Auto Hide" when you pause the mouse over the push-pin.) See Figure 7-11.

    Figure 7-11. The Toolbox and an empty form.

    graphics/07fig11.jpg

  3. From the Toolbox, drag a button, a label, and a text box to the form. See Figure 7-12.

    Figure 7-12. Placing controls from the Toolbox onto a form.

    graphics/07fig12.jpg

  4. Click on Label1 in the Forms Designer. This will select that control. The Properties window, just beneath the Solution Explorer, can be used to make changes to properties of controls. Change the Name property to lblName and the Text property to "Your Name:". After you type the desired value, hit the carriage return. Figure 7-13 shows the Properties window after you have changed the properties of the first label.

    Figure 7-13. Changing property values in the Properties window.

    graphics/07fig13.jpg

  5. Enter property values for the remaining controls and the form as shown in Table 7-1.

    Table 7-1. Property values for the Greeting form
    Control Type Name Text
    Textbox txtName (blank)
    Button btnClickMe Click Me
    Form MainWindow Second Program
  6. Change the file name that will be used for the form by right-clicking on the form in the Solutions Explorer window and choose Rename from the menu. Name the file MainWindow.vb .

  7. Resize the form to the size desired by dragging the sizing handles on the middle of each side. (If they don't appear, select the form by clicking on it first.)

  8. Reposition the controls on the form as desired by dragging them with the mouse. You can manually resize the controls and try to align them, or you can use the Format menu. To use the Format menu:

    1. Select two or more controls using the mouse. Hold down the control key as you click on each control.

    2. The last control you select will have darker handles indicating it has focus and will be the "dominant" control regarding formatting.

    3. You can use the Format Make Same Size Height menu to make all selected controls have the same height as the dominant control.

    4. You can use the Format Align Top menu to align all selected controls along the same top position as the dominant control.

    5. There are many other options under the Format menu that you should investigate in order to produce professional-quality window designs. There is also a Layout toolbar you can use to gain access to control layout and formatting features.

  9. Set the tab order of the controls by using the View Tab Order menu. Click on each control in the order that you want to tab through the controls. (Always put labels just before the control they label in the tab order.) See Figure 7-14.

    Figure 7-14. Setting the tab order of controls on a form.

    graphics/07fig14.jpg

  10. When you are satisfied with the appearance of your form, save the project. Your form should now look similar to Figure 7-15.

    Figure 7-15. A form for the Greeting application.

    graphics/07fig15.jpg

  11. Add an event handler for your Click Me button by double-clicking on the button.

  12. In the handler procedure that was generated, add the following code:

     Private Sub btnClickMe_Click(ByVal sender As _  System.Object, ByVal e As System.EventArgs) _  Handles btnClickMe.Click  MessageBox.Show("Hello " & txtName.Text, "Greeting")  End Sub 
  13. Build the application. You will get the following error because you have changed the name of the default form that was generated for you. You must change the startup form to MainWindow . To do this right-click on the project in the Solution Explorer window and select Properties. See Figure 7-16.

    Figure 7-16. Setting a project's Startup form.

    graphics/07fig16.jpg

     Startup code 'Sub Main' was specified in 'Greeting.Form1', but 'Greeting.Form1' was not found. 
  14. Build and run the application. It should behave like the ByHand program seen in the previous section.

Design Window and Code Window

To be effective using Windows Forms projects in Visual Studio, you should understand how to easily switch between the Design window, where you work with controls on a form, and the Code window, where you work with source code. To bring up the Code window, click on the View Code graphics/view.jpg toolbar button in the Solution Explorer. You may also go back to the Design window by clicking on the View Designer graphics/designer.jpg toolbar button.

Visual Studio .NET indicates the windows that are open using horizontal tabs at the top of the principal window area. You can use these tabs to select among the open windows. Figure 7-18 in the next section shows the open Code window and a tab along the top indicating the Design window for that form is also open.

Adding Event Handlers Using Visual Studio

There are two main ways you can add event handlers in Visual Studio. The simplest is to double-click on a control, which will add the handler for the "primary" event associated with a control. For example, the primary event of a button is Click and the primary event of a form is Load . But a control may have many different events. You can use two dropdown lists at the top of the Code window to add other event handlers. In the left-side dropdown you can select the control, and in the right-side dropdown you can select the event. For adding event handlers for the form itself you can choose (Base Class Events) in the left-side dropdown. Figure 7-17 illustrates adding a handler for the Closing event.

Figure 7-17. Adding a handler for the Closing event.

graphics/07fig17.jpg

Life Cycle of a Windows Form

Sometimes you need to add initialization code to run when a form is first displayed and cleanup code to run at the time the form is closed. You could add initialization code to the constructor of the form. For a Visual Studio .NET Windows application you could also add the code to the InitializeComponent method (discussed in the next section). Both of these approaches involve tweaking code generated by Visual Studio that is normally hidden. A third option for initialization, and the most common, is the handler of the Load event.

There are two events associated with closing a form. The first is Closing . At this point you can still block the closing of the form. For example, you may want to prompt the user to save open files. The second event is Close . At this point the form is about to close and there is nothing you can do to stop it. The program LifeCycle\Version 1 illustrates handling the Load , Closing , and Close events. The event handlers simply display a message box.

 graphics/codeexample.gif Public Class LifeCycle    Inherits System.Windows.Forms.Form    ...    Private Sub LifeCycle_Load(_     ByVal sender As System.Object, _     ByVal e As System.EventArgs) Handles MyBase.Load  MessageBox.Show("Loading")  End Sub    Private Sub LifeCycle_Closing(ByVal sender As Object, _     ByVal e As System.ComponentModel.CancelEventArgs)_     Handles MyBase.Closing  MessageBox.Show("Closing")  End Sub    Private Sub LifeCycle_Closed(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles MyBase.Closed  MessageBox.Show("Closed")  End Sub End Class 

Overriding Virtual Methods of a Form

The Form class has a number of protected overridable methods OnXxxxx, whose base class implementation raises the Xxxxx event. Thus the OnLoad method raises the Load event, and so forth. This means that you could also perform initialization in OnLoad as well as in a handler for the Load event.

Which approach is better? In some documentation you will see that Microsoft recommends overriding the virtual method. This approach is indeed slightly more efficient. But if you do override the virtual method, you must call the base class method, or else the corresponding event will not get raised, which may introduce bugs into your program. You may find it less error-prone to simply handle the event.

You can add overrides in Visual Studio in a manner similar to adding event handlers. In the left-side dropdown in the Code window choose ( Overrides ), and in the right-side dropdown select the method you want to override.

The program LifeCycle\Version 2 illustrates overriding the OnLoad , OnClosing , and OnClose methods and also handling the corresponding events. An interesting feature of this program is that it is built as a console application. The only difference between a console application and a Windows application is that the former will provide a console into which you can write with methods such as System.Console.WriteLine . If the proper Windows Forms code is present, the console application will display a window. Here is the code for this sample application. In place of using a message box to display output, we make calls to Console.WriteLine . Also note that we are careful to call the base class method in all our override methods.

 graphics/codeexample.gif Public Class LifeCycle    Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code " ...    Private Sub LifeCycle_Load(_     ByVal sender As System.Object, _     ByVal e As System.EventArgs) Handles MyBase.Load  Console.WriteLine("Loading")  End Sub    Private Sub LifeCycle_Closing(ByVal sender As Object, _     ByVal e As System.ComponentModel.CancelEventArgs) _     Handles MyBase.Closing  Console.WriteLine("Closing")  End Sub    Private Sub LifeCycle_Closed(ByVal sender As Object, _     ByVal e As System.EventArgs) Handles MyBase.Closed  Console.WriteLine("Closed")  End Sub    Protected Overrides Sub OnClosed(_     ByVal e As System.EventArgs)       Console.WriteLine("OnClosed")  MyBase.OnClosed(e)  End Sub    Protected Overrides Sub OnClosing(_     ByVal e As System.ComponentModel.CancelEventArgs)       Console.WriteLine("OnClosing")  MyBase.OnClosing(e)  End Sub    Protected Overrides Sub OnLoad(_     ByVal e As System.EventArgs)       Console.WriteLine("OnLoad")  MyBase.OnLoad(e)  End Sub End Class 

Here is the console output:

 OnLoad Loading OnClosing Closing OnClosed Closed 

As an experiment, you may wish to comment out the calls to the base class methods and run the program again.


Team-Fly    
Top
 


Application Development Using Visual BasicR and .NET
Application Development Using Visual BasicR and .NET
ISBN: N/A
EAN: N/A
Year: 2002
Pages: 190

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net