IS 350 LAB
CREATING A WINDOWS FORMS APPLICATION

Abstract

In this lab, you will create a first Windows Forms application with a visual interface. You will perform the following tasks:

  • Create a new Windows Forms application
  • Create the application’s user interface using various Visual Basic controls
  • Create the “code behind”that will execute as the developer clicks the buttons that comprise the user interface.

Key Terms

  • Control: A control is an object that typically has a visual interface drawn on a form. A control, like other classes, supports properties and methods, and can handle events.
  • Event handler:An event handler is a Sub procedure that is bound to a control instance, such as a button. An event handler is marked with the Handles class at the end of the procedure declaration.
  • Form: A form is the container for the application’s user interface. A form typically has a border, a title bar, and contains controls. An application can have many forms.
  • Property: A property stores data about an object. The Caption property of a Label control, for example.
  • Properties window: The Properties window is used to set design-time properties forms and the control instances created on a form.
  • Toolbox: The Toolbox contains the .NET controls, which are drawn on a form.
  • Windows Forms Designer: The Windows Forms Designer displays the visual interface for a form as it will be rendered on the screen.

Creating a Windows Forms Application

In this section, you will create a new Windows Forms Application. The process is very similar to the process that you used in the first lab to create a Console application. However, you will use a different template – a Windows Forms Application template.

HANDS-ON STEP: Creating a Windows Forms Application project:

  1. Click File, New, Project to display the New Project dialog. Select theWindows Forms Applicationtemplate. Name the project accordingly.I suggest that you save the Solution and Project to a USB stick or your StudentHome directory. Do not save projects to the Desktop!!!

    Visual Studio creates a solution and project from its template. However, the files created are very different as the following figure shows:
  • Windows Forms Application projects are made up of one or more windows called forms. A form has two parts: the user interface (form) and the code behind the form. You develop a user interface by drawing controls on forms. As you do, Visual Studio writes code in the Form1.Designer.vb file. The Form1.vb file contains the code that you write.
  • The form’s user interface is made up of a rectangular window containing visual objects such as buttons, check boxes, lists and other visual metaphors. These visual objects are called control instances. Control instances are created from controls appearing in the Toolbox. The Windows Forms Designer appears in the center of the screen. It displays a visual representation of a form and its controls.
  • The Toolbox, appearing along the left margin, contains controls that are drawn on a Visual Basic form. To create a control instance on a form, you drag the control from the Toolbox to the form’s visible region (Windows Forms Designer).
  • The Code Editor (not shown in the figure), contains the Visual Basic code that will execute as the user interacts with the form. This is the same code editor that you used in the first lab.
  • As you saw in the first lab, the Solution Explorer manages the files that comprise the solution and project.

Creating a Windows User Interface

Next, you will create the user interface for the application. When complete it should look similarto the following. For the purposes of this lab, don’t worry if your user interface does not precisely match the one shown in the following figure. The learning objective for this exercise is to create the user interface and set its design-time properties.

Creating the user interface for an application is fairly intuitive. The task can be reduced down to the following steps:

  • You drag controls from the Toolbox to the Windows Form Designer.
  • Click a control instance to activate it.
  • Use the sizing handles to change the size of the active control instance.
  • Use the Properties window to set the design-time properties of the selected control instance(s). Multiple control instances can be selected by holding down the Shift key, and clicking the control instance to select.

Control instances work just like the classes and methods you used in the first lab. That is, you can call methods and read and write properties. Some of these properties are operative while a program is being run. Other properties are operative while a program is being designed.

In this lab, you will work with the following controls:

  • The Button control is a clickable button. You typically write code that executes when the user clicks the button.
  • The Label control displays textual output or textual prompts. The Label is a read-only control. Text cannot be entered into a Label.
  • TheOpenFileDialog control displays a dialog box from which the user can select a file. The OpenFileDialog control does not open file. It merely selects a file name as a string. It is up to your program to open files and then process them in some way.
  • The PictureBox control is used to display images.

Working with Design-time Properties

All objects support properties. A property stores data about an object. To get started, a form itself is a class that supports several properties. In this lab, you will work with the following a few of them:

  • The FormBorderStyle property defines the behavior of the form’s border. It can be set to a list of constant values. This constant values appear in the drop-down list in the Value column of the Properties window.
  • The Text property contains a string that is displayed in the form’s title bar.

While the program is being designed, you set the value of a property using Properties window shown in the following figure:

Working from the top-down, the Properties window is made up of the following parts:

  • From topmost drop-down box, you can select an object. The form and the control instances on the active from (in the Designer), appear in the list.
  • The Toolbar has buttons that control the display.
  • The first button (Categories), causes the properties to be displayed in categories based on their function.
  • The next button (Alphabetical), causes properties to be displayed in alphabetical order.
  • The Properties button toggles the display to display properties instead of events.
  • The Events button toggles the display to display events instead of properties.
  • The main window is made up of two columns. The left column lists the property names. In the right column you can edit a property’s value. The Properties window supports different editors based on the data type of property’s value.
  • The lower section displays help for the selected property.

HANDS-ON STEP: Setting properties for the Windows form:

In the following set of steps, you will set the properties for the application’s form.

  1. Make sure that the Windows Forms Designer is active for the main form named form1. If it is not, select the form in the Solution Explorer. On the menu bar, click View, Designer.
  2. The Properties window should be visible. If it is not, pressF4 or click View, Properties from the menu bar.
  3. Make sure that the Properties button is selected and the Alphabetical button is selected.

  4. In the Value column (second column), select the FormBorderStyle property. A drop-down list appears. Select Fixed3D. This value gives the form a 3D border that cannot be resized while the program runs.

  5. Set the Text property to the string DisplayPictures. Note the title bar of the form is updated in the Windows Forms Designer. Most properties are updated in this way. When you set the value of a property, it is updated in the visual designer.
  6. Set the MaximizeBox property to False. This causes the Maximize box on the title bar to be disabled.

Creating Control Instances and Setting their Design-time Properties

In the following steps, you will create the user interface by creating the form’s control instances and setting the design-time properties of those control instances. Generally speaking, you can create the user interface in any order that you want. For example, you can create all of the control instances thereby laying out the form, and then set the properties for the various control instances. Or you can create each control instance and set its properties.

HANDS-ON STEP: Creating control instances:

In the following sequence of steps, you will create the form’s user interface.

  1. Create the first instance of the Label control by first clicking the Label control in the Toolbox. Click View, Toolbox, if necessary, to make the Toolbox visible.
  2. In the Toolbox, drag a Label control instance to the Windows Forms Designer. Click and hold down the left mouse button to draw the control instance on the form.
  3. Note that the Toolbox can be pinned or not pinned to the margin. Click the pushpin button on the title bar. The window becomes auto-hidden. Click Toolbox along the left margin. Click the pushpin again to re-pin the Toolbox.

  4. Create a second Label control instance to the right of the control instance that you just created.
  5. Create an instance of the PictureBox control.
  6. Create six instances of the Button control along the right side of the form.
  7. Create an instance of the OpenFileDialog control on the form. Because the control instance is not visible at run time, it appears in the resizable component tray below the form.
  8. Using the alignment tools discussed in the concept lesson, align and resize the control instances to match the above figure.

HANDS-ON STEP: Setting control instance properties:

In this sequence of steps, you will set the properties for the control instances that you created in the previous steps:

  1. In the Windows Forms Designer, click the Label control instance named Label1.Sizing handles surround the selected control instance. Note that if you accidentally double-click the Label, the Code Editor will be activated. If this happens, close the Code Editor.
  2. Activate the Properties window for the control instance, if necessary, by pressing F4.
  3. In the Properties window, set the AutoSize property to False.
  4. Set the Name property to lblPromptFileName. Set the Text property to File Name: Set the BorderStyle property to FixedSingle.
  5. Locate the Font property in the Properties window. Click the Value column. Click the Build button (the button with the ellipses) to display the Font dialog box. Set the font style to Bold, and then click OK to close the dialog box.
  6. Locate the BackColor property in the Properties window. Click the Value column. Click the List arrow, click the Custom tab, and then select the first row, first box. When you click the color, it is applied as the background color behind the label text.
  7. Locate the TextAlign property in the Properties window, and then click the Value column. Using the visual editor, select MiddleRight.
  8. In the Windows Forms Designer, click the Label control instance named Label2. Set the Name property to lblFileName. Remove the text from the Text property.
  9. Set the remaining properties to the same values you used for the control instance named lblPromptFileName.
  10. Activate the Properties window for the picture box. Rename the picture box so that it is named picCurrent. Set the BorderStyle property to FixedSingle.
  11. Rename the OpenFileDialog control instance so that it is named ofdImages.
  12. Set the properties for the remaining control instances, as shown in the following table. Use the Object drop-down box in the Properties window to select the control instances. Note that the ampersand character marks the button’s hot key.

Creating an Event Handler

In this part of the exercise, you will write the code that will execute when the user clicks the various buttons. This code is referred to as an event handler. An event handler is a Sub procedure that executes in response to an event. In this lab, the event handler will respond to a Button’sClick event. Note that Windows supports many events and you will create various event handlers in subsequent labs.

The above code fragment illustrates an event handler.

  • Event handlers are always Sub procedures. Sub procedures do not return a value.
  • .NET event handlers always have two arguments.
  • The first has a data type of System.Object. The first argument stores a reference to the object that caused the event to occur.
  • The second has a data type of EventArgs. The second argument, as you will see in subsequent labs, is used to pass data about the event.
  • The Handles clause indicates that the procedure is an event handler. Following the Handles clause is event handler name (btnDisplayImage.Click). In the above example, the procedure appears in the form class named Form1. The event handler name is made up of the control instance name, followed by a period, followed by the event name. If you remove the Handles clause, the procedure will no longer operate as an event handler.

There are a couple of different ways to create an event handler:

  • If you double-click a button in the Windows Forms Designer, Visual Studio will create the Click event handler. This procedure will also create the default event handler for other control instances too.
  • In the Code Editor, select the object and event from the drop-down boxes. Visual Studio will create the desired event.
  • In the Properties window, selected Events mode. Then, in the Value column, double-click on the event that you want to create.

Next, take a close look at the code for the event handler that will display an image.

ofdImages.ShowDialog()
lblFileName.Text = ofdImages.FileName
picCurrent.Image = _
System.Drawing.Image.FromFile(ofdImages.FileName)

  • The first of the preceding statement displays the open file dialog box allowing the user to select a file. The OpenFileDialog is named ofdImages. The method name is ShowDialog().
  • The second statement is an assignment statement. The right side of the expression (ofdImages.FileName) reads the FileName property of the OpenFileDialog named ofdImages. This value is assigned to the Text property of the Label named lblFileName. Objects and their properties are always connected by a period (.).
  • The final statement is also an assignment statement. The right side of the assignment reads the image stored in the file. That image is assigned to the Image property of the PictureBox named picCurrent. Recognize that the right side of the expression returns a data type of Image, which is the same data type as the Image property on the left side of the expression. When writing assignment statement, the data types of the expressions on the left and right side of the assignment statement must match.

HANDS-ON STEP: Creating and coding the event handlers:

  1. In the Windows Forms Designer, double-click the Display Imagebutton (the one with the ellipsis). Visual Studio creates the Click event handler for the button and activates the Code Editor.
  2. Enter the following statements (shown in bold) in the event handler:
    ofdImages.ShowDialog
    lblFileName.Text = ofdImages.FileName
    picCurrent.Image = _
    System.Drawing.Image.FromFile(ofdImages.FileName)
    The first of the preceding statements displays the OpenFileDialog. The second statement stores the filename selected by the end user in the Label control instance named lblFileName. The final statement displays the image in the PictureBoxcontrol instance. A continuation line is used in the last statement.
  3. Open a Web browser and download an image of your choosing to the local folder where the project resides. To download an image, right-click the image in the browser, and select Save Image As (Chrome).
  4. Run the program. Click the button with the ellipses. The OpenFileDialog should appear. Select an image file. It should appear in the PictureBox control instance.

Next, you will create the Clickevent handler for the Clear button. The code in this event handler will remove the image currently displayed in the control instance by setting the Imageproperty to Nothing.Nothing is a Visual Basic keyword that clears an object reference. So instead of referencing an image, the Image property references Nothing. This process will become clearer when you learn about the difference between value types and reference types.

  1. Create the Clickevent handler for the Clear button, and then enter the following statements:
    lblFileName.Text = ""
    picCurrent.Image = Nothing

The first of the preceding statements sets the Text property of the Label control instance
named lblFileName to an empty string.

  1. Next, the event handler for the Exit button needs to be created. The code in this event handler will exit the application:Create the Clickevent handler for the Exit button, and then enter thefollowing statement. The Me keyword references the current class, which in this case is the form. The Close() method of the Form class closes the form, thereby ending the application.
    Me.Close()

The next group of statements that need to be written define how the imagewill appear in the PictureBoxcontrol instance. Each of these statementswill set the SizeModeproperty to a different enumeration value.