PUTTING TOGETHER A GRAPHICAL USER INTERFACE


The first thing users typically see when they start up a Windows application is its graphical user interface. Today, most users have enough experience working with computers running Windows that they approach each new application with certain expectations. For starters, they expect application windows to be well organized and clearly presented. Users also expect other things, such as being able to tab between controls in a logical order and to see messages displayed in a status bar located at the bottom of windows.

Users also want to be able to move the pointer over a control in order to see a ToolTip explaining what the control does. Users expect to see a unique icon representing your applications' executable file, and they may also want to see that icon posted in the Windows taskbar's System Tray. In short, they expect your Visual Basic application to provide the same basic features that are found in most other Windows applications. In this chapter, you will learn how to implement each of the features described above. Depending on the type of application you are working on, users may also expect to see menus and toolbars. You'll learn how to add these types of controls to your Visual Basic application in Chapter 4, "Working with Menus and Toolbars."

Specifying a Windows Starting Position

By default, Windows opens your Visual Basic application's windows at the location of its choice. Sometimes this is in the middle of your screen, sometimes it's not. However, if you want, you can exercise control over the screen position that Windows chooses. This is accomplished by setting the form's StartPosition property. The StartPosition property can be set to any of the values shown in Table 3.1.

Table 3.1: Values Supported by the Form Startposition Property

Property

Description

Manual

The form's Location property determines where the form is displayed and the form's size property specifies its bounds.

CenterScreen

The form is centered in the middle of the screen and the form's size property specifies its bounds.

WindowsDefaultLocation

Displays the form at a location chosen by Windows but the form's size property specifies its bounds.

WindowsDefaultBounds

Displays the form at a location chosen by Windows using bounds (size) also chosen by Windows.

CenterParent

The form is centered within the bounds of its specified parent, which could be the Windows desktop or another form in the application.

By specifying one of the values shown in Table 3.1 at design time, you can exercise various levels of control over where your form is initially displayed and in what size it will appear.

Specifying Windows Border Style

By default, Visual Basic allows users to resize a form's window border at run time, However, this can result in some undesired consequences, as demonstrated in Figure 3.6. As you can see, once resized, the window shown in Figure 3.6 suddenly looks very unprofessional, with far too much empty space on the right-hand side of the window.

image from book
Figure 3.6: Unless you specify otherwise, Visual Basic will allow users to change the size of your application's window.

The easiest way to deal with this situation is to control the form's border style using the FormBorderStyle property. Table 3.2 outlines each of the available FormBorderStyle property values.

Table 3.2: Available Options for the Formborderstyle Property

Value

Description

None

Displays the form without a border

FixedSingle

Sets up a fixed single line form border

Fixed3D

Sets up a fixed three-dimensional form border

FixedDialog

Sets up a thick fixed form border

Sizable

Sets up a resizable border

FixedToolWindow

Sets up a tool window border that cannot be resized

SizableToolWindow

Sets up a tool window border that can be resized

Dynamically Altering Title Bar Messages

Unless you change a form's Text property, Visual Basic displays the name of the form in its title bar, as shown in Figure 3.7.

image from book
Figure 3.7: By default, Visual Basic displays a form's name in its title bar.

image from book
DEFINITION

A tool window is one that does not appear in the Windows taskbar when the application is running.

image from book

Typically, you will set the form's Text property to display any text string you wish using the Properties window. In addition, you can set it with code at run time, as demonstrated below.

 Private Sub Button1_Click(ByVal sender As System.Object, _   ByVal e As System.EventArgs) Handles Button1.Click         Me.Text = "Speed Typing Game" End Sub 

This code is associated with the click event belonging to the Button1 control on the form. When the button is clicked, the code executes, updating the text string displayed in the title bar, as shown in Figure 3.8.

image from book
Figure 3.8: Programmatically changing the text string displayed in the window's title bar.

Trick 

Note the use of the keyword Me in the previous example. Me is a Visual Basic keyword that refers back to the parent object that is currently executing, which in the case of the previous example was form1.

By programmatically changing the text string displayed in the form's title bar using code, you create the ability to dynamically change its contents. However, you should exercise this capability very carefully. Most users don't look at the title bar, and even when they do, they don't go back and view it over and over again, so they'll miss any text changes that you have posted to it.

Trick 

If you plan to post dynamic text content, you should look at setting up a status bar on your form, as discussed later in this chapter.

Setting Up Control Tab Order and Focus

Users can interact with controls that appear on your Visual Basic applications by using their mouse to click on or select them. However, users can also use the keyboard Tab key. By repeatedly pressing the Tab key, focus is transferred from control to control. You can visually tell which control has focus by examining it. Controls such as buttons are highlighted when they receive focus, whereas controls such as textboxes display a blinking cursor.

The tab order between controls is based, by default, on the order in which you add the controls to the form. Each time you add a control to a form, it is assigned a tab index number. The first control added to the form is assigned an index number of 0, and each control that is added after that is assigned an index number that is incremented by 1. So by carefully adding controls to a form in the exact order in which you wish them to be accessed via the Tab key, you can control the form's tab order. However, in most cases this option is too bothersome to try and implement. Instead, most programmers add controls in any order they wish and then come back and specify the tab order.

image from book
DEFINITION

Focus is a term used to identify the currently selected control (the control that will receive any keyboard input).

image from book

Trick 

By default, each control's TabStop property is set to True. If you set this property to False, your application will not include the control in the tab order.

One way to modify tab order, after you have added all the controls to a form, is to set each control's TabIndex property. Specify 0 for the default control (the control that initially receives focus when the form loads) and 1 for the control that will be the next control in the tab order. However, a better way to specify tab order is to click on the View menu and select the Tab Order option. This tells the IDE to display numbers in the corner of each control representing each control's order within the tab index, as demonstrated in Figure 3.9.

image from book
Figure 3.9: Modifying the default tab order of the controls located on a Visual Basic form.

To modify the tab order, just click on the control that should be first, followed by each remaining control in the order that you wish them to be ordered. When done, click on the Tab Order option located on the View menu a second time to remove the tab order indicators.

Adding a Status Bar to Your Application

One feature that you may wish to add to windows in your Visual Basic applications is a status bar. A status bar is a window control, typically located at the bottom of a window where applications display all sort of information as they run. Examples of information commonly displayed by status bars include the current date and time, help information, hints, error information, or the name of a currently open file.

Trick 

Although the IDE automatically places the status bar at the bottom of the form by default, you can move it to any edge of the form by setting the Dock property, which supports any of the following values: Right, Left, Top, Bottom, and Fill.

A status bar can display different types of data, including text and icons. Status bars can also be divided up into panels, enabling one status bar to display many different types of information, each in its own defined section of the status bar, as demonstrated in Figure 3.10.

image from book
Figure 3.10: A Windows status bar displaying the current date and application status information in two separate panels.

In order to add a status bar to a window in a Visual Basic application, you must add the StatusBar control from the Toolbox to the appropriate form. Once added, you can configure the StatusBar control by modifying any of the properties shown in Table 3.3.

Table 3.3: Configuring Properties Belonging to the Statusbar Control

Property

Description

Text

A text string to be displayed in the status bar

SizingGrip

A visual indicator in the right-hand corner of the status bar indicating that it can be resized

Panels

Adds or removes panels from the status bar

ShowPanels

Determines whether the status bar displays panels

To get a better understanding of how to work with the StatusBar control, let's work on a couple of examples. In order to use the StatusBar control you must first add it to your ToolBox window, as outlined in the following procedure.

  1. Right-click on the Toolbox window and select Choose Items from the context menu that appears.

  2. The Choose Toolbox Items window appears. By default the .NET Framework Components tab is selected.

  3. Scroll down and select the StatusBar control.

  4. Click on OK.

Once you have added the StatusBar control to the Toolbox windows, you can add a status bar to your application and write some text for it, as outlined below.

Hint 

You can also implement a status bar on your application using the StatusStrip control. For information on how to use this control, refer to Visual Basic's online help.

  1. Create a new Visual Basic application.

  2. Add a Button control and a StatusBar control to your application's form.

  3. Modify the button's Text property to Push me.

  4. Select the StatusBar control and then modify its Text property to display the string Hello World!

Now, press the F5 key to run your application, and you should see that Hello World! is displayed in the left-hand side of the status bar. Stop your application in order to return to design mode. Next, let's modify the application's status bar by organizing it into two panels and displaying separate pieces of information in each panel as outlined below.

Trap 

You might want to set the StatusBar control's SizingGrip property to False if you plan on preventing users from being able to resize your application window. Otherwise, your users are going to get confused.

  1. Select the StatusBar control and then set its ShowPanels property equal to True.

  2. Next select the Panels property and click on the ellipsis () button shown in its value field to open the StatusBarPanel Collection Editor window.

  3. Click on the Add button to define the first panel. A panel named StatusBarPanel1 will be displayed in the Members pane.

  4. Modify the StatusBarPanel1 object's Text property for the first panel to say Ready.

  5. Modify the StatusBarPanel1 object's AutoSize property to equal Spring.

  6. Click on the Add button again to define a second panel. By default, the panel will be named StatusBarPanel2.

  7. Modify the StatusBarPanel2 object's Text property of the second panel to say Click on the button.

  8. Modify the StatusBarPanel2 object's AutoSize property to equal Spring.

  9. Click on OK to close the StatusBarPanel Collection editor.

Trick 

You can control the amount of space allocated to each status bar panel by specifying any of the following values for the AutoSize property.

  • None. Does not display a border

  • Spring. Shares space with other panels that have their AutoSize property set to Spring

  • Contents. Sets panel width based on its current contents

Press F5 to run your application. Now your application's status bar displays two separate pieces of information, each in its own status bar panel. Or course, to make a status bar truly useful, most applications need to be able to dynamically change its contents as the application runs. For example, if you have defined a status bar named StatusBar1 that does not have any panels, you could add the following statement to the click event of the Button control. When clicked, the text Hello World! is displayed in the status bar.

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As  System.EventArgs) Handles Button1.Click           StatusBar1.Text = "Hello World!" End Sub 

If, on the other hand, you organized your status bar into multiple panels, you could place a text string in each panel by adding the following statements to the click event of the Button control.

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click         StatusBar1.Panels(0).Text = "Hello World!"         StatusBar1.Panels(1).Text = "Today is " & Now() End Sub 

Trick 

Now retrieves the current date and time as set on the computer running your Visual Basic application.

As you can see in Figure 3.11, the StatusBar control organizes panels into a collection, assigning each panel in the collection an index. The first panel has an index of 0. The next panel has an index of 1, and so on. Each StatusBarPanel object in the collection is its own object and can display its own content. To write a text string to a particular panel, you must specify its index position within the collection. Figure 3.12 shows how the two-panel example from above looks after the user has clicked on the button.

image from book
Figure 3.11: Using the StatusBarPanel Collection Editor, you can organize a status bar into any number of panels.

image from book
Figure 3.12: Status bars provide an effective tool for communicating information with users.

Trick 

If you wish, you can set up your application so that it can respond when the user clicks on the status bar. This is achieved by adding whatever code you wish to the Click or PanelClick events, depending on whether you have set up a simple or panel-based status bar.

 Private Sub StatusBar1_PanelClick(ByVal sender As System.Object, _        ByVal e As System.Windows.Forms.StatusBarPanelClickEventArgs) _        Handles StatusBar1.PanelClick          MessageBox.Show("Status bar has been clicked.") End Sub 

Posting a NotifyIcon in the System Tray

Using a NotifyIcon control, you can add or remove an icon representing your Visual Basic application in the System Tray, as demonstrated in Figure 3.13. By placing an icon in the System Tray, you provide the user with an alternative way of communicating with your Visual Basic applications. For example, you might want to place an icon in the System Tray in the event that an error occurs in your application when it is in a minimized state. Alternatively, you might make the icon blink in order to catch the user's attention. You can even set things up so that your application reappears when the user clicks or double-clicks on the icon.

image from book
Figure 3.13: The Windows System Tray provides single-and double-click access to various Windows utilities, processes, and applications.

image from book
DEFINITION

The System Tray is an area located on the far right-hand side of the Windows taskbar that displays icons representing active system processes, utilities, and applications.

image from book

NotifyIcon are implemented by adding a NotifyIcon control from the Toolbox onto your form. Actually, the NotifyIcon component will appear on the component tray, just below the IDE form designer. Once added, you can edit its properties, which include:

  • Icon. Specifies the name and location of the icon to be displayed in the System Tray

  • Text. Specifies text to be displayed as a ToolTip when the user moves the pointer over the icon

  • Visible. Enables or disables the display of the icon in the System Tray

By default, the visible property is set equal to True at design time, meaning that the application's NotifyIcon will be displayed as soon as your application begins to execute. You can programmatically enable the display of the NotifyIcon by executing the following statement where appropriate in your application code:

 NotifyIcon1.Visible = True 

Alternatively, you can disable the display of the NotifyIcon as demonstrated below.

 NotifyIcon1.Visible = False 

Trick 

To grab the user's attention, you can create a Look that alternates the execution of the two previous statements every second, thus causing the icon to blink repeatedly in the System Tray. You will learn how to work with loops later, in Chapter 7, "Processing Lots of Data with Loops."

You can also set up your application to react to events, such as the Click and DoubleClick events for the NotifyIcon, as demonstrated below.

 Private Sub NotifyIcon1_MouseDown(ByVal sender As System.Object, _       ByVal e As System.Windows.Forms.MouseEventArgs) _       Handles NotifyIcon1.MouseDown         MessageBox.Show("The Notify Icon has been clicked.") End Sub 

Adding a Splash Screen to Your Application

One thing that you might want to do to spice your application up a bit is to give it a splash screen. The IDE makes the creation and setup of a splash screen very straightforward. All that you have to do is create a new form and then tell the IDE to make it your application's splash screen.

image from book
DEFINITION

A splash screen is a window that appears briefly when an application first loads. Application developers use splash screens to display product information or to distract users while their application loads.

image from book

The following example demonstrates the steps involved in adding a splash screen to your Visual Basic applications.

  1. Open a new Visual Basic Windows application project and expand the default form to approximately twice its normal size to make it distinguishable from its splash screen. Place whatever controls you wish on it.

  2. Click on the Project menu and select the Add Windows Form option. The Add New item window appears.

  3. Select the Splash Screen icon from the available list of templates, enter SplashScreen.vb as the Window's name in the Name field, and click on the Add button.

  4. The IDE will display the SplashScreen form. By default is will already have its BackgroundImage property set to display a graphic depicting three intertwined rings. You can change this property to use any bitmap image you wish.

  5. Visual Basic automatically displays text on the Splash Screen window representing your application's name, version and copyright date. You do not need to modify this information. Visual Basic will automatically fill their values for you.

  6. Click on the Properties option located at the bottom on the Project menu. A new window will appear in the IDE.

  7. Make sure that the Application tab is displayed as shown in Figure 3.14.

  8. Using the Splash screen drop-down list at the bottom of the window, select SplashScreen as your application's splash screen.

image from book
Figure 3.14: Configuring a Visual Basic application to begin by displaying a splash screen.

Now, close the Properties Window and press F5 to run your application. Just before the main menu starts, you should briefly see your splash screen appear. After a moment, it will close and your application's main windows will be displayed, as demonstrated in Figures 3.15 and 3.16.

image from book
Figure 3.15: A splash screen gives the application developer a chance to share additional information with the user before the application starts.

image from book
Figure 3.16: The application's main window appears as soon as the splash screen closes.

Leveraging the Convenience of Built-in Dialogs

In some applications, you may want to interact with and collect information from the user using more than one window. One way to accomplish this is to create additional forms and to call upon each form when needed. You've just seen one way to do this using a splash screen. You'll learn how to create and display your own custom windows in later chapters. Another option available to you is to take advantage of a couple of built-in options for displaying pop-up windows.

The MessageBox.Show Method

Sometimes all your application may need to do is ask the user a simple question. You can always add controls to a form to collect this information, or even create a new form especially for this purpose. Optionally, you may be able to collect the information you want using the MessageBox.Show method, which is made available through the .NET Framework. The MessageBox.Show method is used to display a pop-up window that contains a custom text message along with an icon and buttons.

Figure 3.17 provides an example of the kind of pop-up window the MessageBox.Show method is capable of producing. As you can see, it supports a number of different features.

image from book
Figure 3.17: The MessageBox.Show method is perfect for displaying a small amount of text information.

The MessageBox.Show method supports 21 different formats, meaning that you can pass it different information in different ways depending on what you want it to do. As a demonstration of this, take a look at Figure 3.18. As you can see, as soon as I typed MessageBox.Show(", IntelliSense kicked in and started offering its assistance in the formulation of the rest of the statement. Take note of the up and down arrows surrounding the 1 of 21 text at the beginning of the first line of text in the IntelliSense window. By clicking on these up and down arrows, you can scroll through and view each of the different variations of the MessageBox.Show method.

image from book
Figure 3.18: Twenty-one different formats of the MessageBox.Show methods are supported.

Regardless of which format of the MessageBox.Show methods you choose to use, they all require the same basic information in order to execute, as outlined in Table 3.4.

Table 3.4: Parameters Available to the Messagebox.Show() Method

Parameters

Description

Text

The text string to be displayed in the pop-up windows

caption

The text string to be displayed in the pop-up window's title bar

Buttons

The button or group of buttons to be displayed in the pop-up window

Icon

The type of icon to be displayed in the pop-up window

DefaultButton

The button that will serve as the default button

Options

Display options that affect how the pop-up window and its text are displayed

The text and caption parameters are simply text strings. The Buttons parameter is used to specify any of six different sets of buttons, as shown in Table 3.5.

Table 3.5: Buttons Available to the Messagebox.Show() Method

Button

Description

AbortRetryIgnore

Displays Abort, Retry, and Ignore buttons

OK

Displays an OK button

OKCancel

Displays an Ok and a Cancel button

RetryCancel

Displays a Retry and a Cancel button

Yes/No

Displays a Yes and a No button

YesNoCancel

Displays a Yes, a No, and a Cancel button

The MessageBox.Show method also allows you to display an icon to further help inform the user about the nature of the pop-up windows and the information it is trying to convey or collect. Table 3.6 identifies the various icons supported by MessageBox.Show.

Table 3.6: Icons Available to the Messagebox.Show() Method

Icon

Description

Asterisk

Displays an Asterisk icon

Error

Displays an Error icon

Exclamation

Displays an Exclamation Mark icon

Hand

Displays a Hand icon

Information

Displays an Informational icon

None

Displays the pop-up window without displaying an icon

Question

Displays a Question Mark icon

Stop

Displays a Stop icon

warning

Displays a Warning icon

You can also specify which button should be used as the default button. You specify which button to make the default button based on its position. Table 3.7 lists the available selections.

Table 3.7: Default Button Value Options for the Messagebox.Show() Method

Button

Description

Button1

Makes the first button the default

Button2

Makes the second button, if present, the default

Button3

Makes the third button , if present, the default

You can also specify any of the values listed in Table 3.8 for the Options parameter.

Table 3.8: Options Values for the Messagebox.Show() Method

Button

Description

DefaultDesktopOnly

Displays the pop-up window on the active desktop

RightAlign

Displays the text in the pop-up windows as right aligned

RtlReading

Displays the text in the pop-up windows as left aligned

To help make the MessageBox.Show method easier to understand, let's look at a few examples. In this first example, I'll create a pop-up window that asks the user a question, displaying Yes and No buttons and the Stop icon. I'll also make the Yes button the default button and right-align the message text (including the caption text).

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click         MessageBox.Show ("Click on Yes to continue or No to Stop.", _           "MessageBox. Show  Example 1", _           MessageBoxButtons.YesNo,  MessageBoxIcon.Stop, _         MessageBoxDefaultButton.Button1, _           MessageBoxOptions.RightAlign) End Sub 

When executed, this example generated the pop-up window shown in Figure 3.19.

image from book
Figure 3.19: Prompting the user for permission to continue.

Next, let's look at an example where I'll only supply the first two parameters. As the following statements show, I only supplied the parameters for the Text and Caption.

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click         MessageBox.Show("This is an informational message.", _           "MessageBox.Show Example 2") End Sub 

When executed, this example generated the pop-up window shown in Figure 3.20.

image from book
Figure 3.20: Displaying a simple Informational message.

In addition to displaying informational messages for users, you can use the MessageBox.Show method to collect and analyze the user's response, as demonstrated in the following example.

 Private Sub Button1_Click(ByVal sender As System.Object, _       ByVal e As System.EventArgs) Handles Button1.Click         Dim UserResponse As String        UserResponse = MessageBox.Show("Please click on a button", _            "MessageBox.Show example 3", _            MessageBoxButtons.AbortRetryIgnore)          MessageBox.Show("You clicked on " & UserResponse) End Sub 

In this example, the user is asked to click on one of the three buttons displayed by the pop-up window. A number representing the button that the user clicked is passed back and stored in a variable name UserResponse. A second MessageBox.Show method is then used to display the user's response as shown in Figures 3.21 and 3.22.

image from book
Figure 3.21: Prompting the user to select from three options.

image from book
Figure 3.22: Viewing the results of the button selection made by the user.

image from book
DEFINITION

A variable is a piece of memory where data is stored by your application as it runs.

image from book

As you can see in Figure 3.22, a numeric value was passed back representing the button that the user clicked on. Table 3.9 defines the range of values that may be returned by the MessageBox.Show method.

Table 3.9: Return Values Associated With the Messagesox.Show() Method

Button

Description

OK

1

Cancel

2

Abort

3

Retry

4

Ignore

5

Yes

6

No

7

Trick 

Visual Basic also supplies the MsgBox function as another tool for displaying information in a pop-up dialog. However, all of the functionality provided by the MsgBox function is already provided by the MessageBox.Show method.

The InputBox Function

Another option for interacting with the user and collecting user input is the Visual Basic InputBox function. The InputBox function provides you with the ability to collect text-based information from the user, as demonstrated in Figure 3.23.

image from book
Figure 3.23: Examining the composition of a pop-up window generated by an InputBox function.

The basic syntax of the InputBox function is shown below.

 X = InputBox(TextMessage, Caption, DefaultResponse, Xpos, Ypos) 

x is a variable used to hold the text string supplied by the user. TextMessage is a placeholder representing the text message you want to display in the pop-up windows. The text message can be up to 1,024 characters long, depending on the length of the letters used. Caption is another placeholder representing the text string you want displayed in the popup window's title bar. XPos and YPos are used to optional specify, in twips, the horizontal and vertical placement of the pop-up windows on the screen.

The following example shows the statements that were used to generate the example shown in Figure 3.23.

 Private Sub Button1_Click(ByVal sender As System.Object, _        ByVal e As System.EventArgs) Handles Button1.Click          Dim UserResponse As String          UserResponse = InputBox("What is your name?", _            "Sample InputBox() Function Example") End Sub 

image from book
DEFINITION

A twip is a unit of measurement approximating a value of 1/1440th of an inch.

image from book

Trap 

Once the user enters a response and clicks on the OK button, the text that was entered is assigned to the variable X. However, if the user clicks on the Cancel button without first entering text, an empty string ("") is returned.




Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
Microsoft Visual Basic 2005 Express Edition Programming for the Absolute Beginner
ISBN: 1592008143
EAN: 2147483647
Year: 2006
Pages: 126

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