Your First Real Visual Basic .NET Program

Your First Real Visual Basic .NET Program

I know you want to write some code. In this section, we'll write a simple program that displays the time of day. While a straightforward and humble goal, writing this program will teach you how the new event paradigm works, let you work with some of the new .NET controls, and build your knowledge of the .NET object model. Of course, this program will also beef up your knowledge of object-oriented programming and the use of namespaces as well as introduce you to some new date arithmetic. One of the great new enhancements to the IDE is the Menu Editor. This is a world-class editor that makes adding menu items a cinch. The running program will look like Figure 2-17.

Figure 2-17

Our program.

  1. Start a new Visual Basic project and select the Windows Application template. Name the project VB .NET Clock, as shown in Figure 2-18.

    Figure 2-18

    The new VB .NET Clock project.

    tip

    As a rule of thumb, always create a new subdirectory for each new project. It's easy to accept the default settings and just click through. But unlike classic Visual Basic, the Visual Basic .NET IDE will actually create a new subdirectory for you with the name of the project. Many novices to Visual Basic would unknowingly create many projects in the same directory, and things got messy fast. Default forms and files were overwritten, and programmers worked on one form only to find that the original had been destroyed. The Visual Basic .NET IDE protects us from ourselves in this respect. If you consciously create a new directory for each new project, the IDE will automatically build the respective subdirectories for you. Keeping your projects separate is not only good programming practice, but when you start working in teams it is critical. Click the Create Directory For Solution check box if a folder does not exist.

    As any professional programmer would do, the first thing you want to do is rename any form and control before writing code for it. Defining a clear, standardized naming convention is always the first step when developing a new program. Gone are the days when you would name a variable HB86 or use your girlfriend's name. In the same vein, Form1 is not very descriptive of what our form does.

    Not only does a consistent naming style enhance the readability of source code and make maintenance of it easier, it also shows how well a developer comprehends a software system. While guidelines you can follow do exist, you should choose a convention that works for you and your team. Most of all, after you choose a style, stick with it in all cases. The saying "A stubborn consistency is the hobgoblin of small minds" does not apply to Visual Basic .NET coding convention practice.

    As I discuss the components of programs such as variables, routines, tables, and the like, I'll suggest some naming conventions and illustrate and explain them. Because we are starting this example with a form, let's call it frmTime instead of the default Form1. This name tells us the object is a form and something about what the object does.

  2. The default form is displayed and the boilerplate code generated. If the Solution Explorer is not visible, click View|Solution Explorer. Right-click Form1.vb, and then select Properties. Change the FileName property from Form1.vb to frmTime.vb, as shown in Figure 2-19.

    Figure 2-19

    Change the form's FileName property to frmTime.vb.

  3. We now want to change the name of the class that creates the time display form. We have to change the default name of Form1 to frmTimeClass. First change the name of the class to frmTimeClass.

    Public Class frmTimeClass    Inherits System.Windows.Forms.Form

  4. Now move down to the region marked #Region Windows Form Designer generated code. This region is where the form's controls are declared. The next name change is to the form's name. Change the name from Form1 to frmTimeClass, as shown here:

    Me.Name = "frmTime"

Telling the Application Object Which Form to Run

The next step in our program is to tell the Application object to run frmTimeClass and not the default, defunct, and extinct Form1. That's easy. Bring up the Solution Explorer again. Right-click the name of the project VB .NET Clock, select Properties, as shown in Figure 2-20, and you'll see the Properties box for the project.

Remember that a project usually consists of separate components that are stored as individual files in a solution. Our simple project consists of a form and a project file. More complex projects might consist of these items plus database scripts, modules, HTML files, stored procedures, and even a reference to an existing Web service.

A project functions as a container from which you can assemble components and deploy a finished application. The output of our project will be an executable program (VB .NET Clock.exe). Later in the book we will create a dynamic-link library (DLL) file and other types of projects. It's important to keep in mind that all projects are contained within a solution. Each project in that solution contains a unique project file. This project file lists the files contained in the project and is used to both store and track other information about those files. Each time you save a project, the project file is updated.

Figure 2-20

The Properties box.

Project property pages are a slick new way of consolidating the information about a project that a programmer can modify. You can see that the default assembly name is the name of the project. The project name is also the root namespace. If you want to include the functionality of this project in another project, you simply need the directive Imports VB .NET Clock. Remember that for a developer, a namespace provides a grouping of related types. Click the Startup Object drop-down box and select the new frmTimeClass form, as shown in Figure 2-21. Click OK.

Figure 2-21

Changing the startup form to frmTimeClass.

Let's Add Some Controls

If you don't see the Toolbox, select View|Toolbox. As I mentioned, all of the controls in Visual Basic .NET have been reengineered and upgraded from the classic .OCX controls. The controls have similar but not identical behaviors to those you might be used to. One of the best enhancements in Visual Basic .NET is that these new controls are not required to be registered. You can forget about RegSvr32 in Visual Basic .NET.

  1. Add a label to the form, and then scroll down in the Toolbox and add a Timer control and a NotifyIcon control from the Toolbox, as shown in Figure 2-22. You'll notice that the IDE places all controls that are either not visible at run time or not part of the form in a region directly below the form. This arrangement is a nice design touch because the form's real estate is not cluttered with controls that are not directly manipulated by the user. Unlike classic Visual Basic, you can now see exactly how the form will look when it is run because these controls will be invisible at run time.

    Figure 2-22

    Add these controls to your form.

    tip

    To be sure you understand how Visual Basic .NET names items, take a look at the caption of the IDE. On the left it indicates that you are working in the project VB .NET Clock. On the right, you can see that you are displaying the file frmTime.vb, which contains our class. The current tab confirms that you are editing the file frmTime.vb in the Forms Designer.

    Because this program will display a clock, we want to eliminate the minimize and maximize buttons on the title bar, as well as the form's built-in Control menu. We make these changes because we don't want users to change the size of our form, which would do nothing except ruin its look. Adding a custom icon might also provide a nice professional touch.

    note

    Purists might say, "Wait! You have to let users decide everything! Users should be able to decide how they want to size the form. Every option that can be given to a user should be." In the real world, however, you should provide users with only sensible choices. In the case of our clock, permitting them to maximize the form to take up the entire screen serves no purpose except to confuse and possibly anger the user. In user interface design, a little bit of programming discipline goes a long way toward a user friendly application. Ironically, everyone thinks they are experts at UI design because it's so easy to make one. Quite the contrary. You will find that creating an elegant human-machine interface is one of the biggest challenges in visual programming.

  2. Go to the Forms Designer and click the form to give it focus. Right-click, and then select Properties. Change the properties of the form as shown in Table 2-5, and then modify the properties on the label, timer, and notify icon as shown. Be sure to change the names of the label, timer, and notify icon controls as shown in the table.

    Table 2-5  Properties for Our Form and Controls

    Object

    Property

    Value

    frmTimeClass

    FormBorderStyle

    FixedDialog

    Icon

    LOCATED: [Drive] Program Files\Microsoft Visual Studio .NET\Common7\Graphics\ Icons\Misc\Watch01.ico

    MaximizeBox

    False

    MinimizeBox

    False

    StartPosition

    CenterScreen

    Text

    VB .NET Time

    Label1

    Name

    lblTime

    BackColor

    Green (choose the color from the Web tab of the drop-down list; it will say Lime)

    BorderStyle

    Fixed3D

    ForeColor

    Blue (choose the color from the Web tab of the drop-down list)

    Text

    ""

    Timer1

    Name

    tiTimer

    Enabled

    True

    Interval

    500

    NotifyIcon1

    Name

    tIcon

    Icon

    LOCATED: [Drive] Program Files\ Microsoft Visual Studio .NET\ Common7\Graphics\Icons\Misc\ Watch01.ico

    Text

    VB .NET Time

    Visible

    True

    After you've changed the properties, the finished product in the design environment should look like Figure 2-23. Even though you've changed only some properties on the form and three controls, you were programming. In classic Visual Basic, changes like these were not always apparent because the code was hidden from you. In Visual Basic .NET, you can see the code generated by the changes you made.

    Figure 2-23

    The completed form.

A user can only dismiss the form using the Close button. Maximizing the form to the size of the screen is impossible. Users can still use the form's drop-down Control menu, but because we removed the ability to resize the form, the menu permits the user only to move or exit the form.

note

Click the green label to give it focus. Select Format | Center In Form | Horizontally to space the label from side to side. Next select Format | Center In Form | Vertically to space the label from top to bottom. Before you deploy any application with a user interface, use the Format options to ensure a balanced, symmetrical look. Controls that are impeccably aligned are the mark of a pro. With the Format options in Visual Basic .NET, there is no excuse.

Thinking About the User Interface

Shortly after the Big Bang, programmers started slinging code. Only when the code was complete did a programmer start to think about a user interface. The UI was almost always an afterthought. Now that the earth has cooled and the world has moved to visual programming languages such as Visual Basic .NET, the first step in programming is to design and draw the user interface. After all, the interface is the program to your users. The user has absolutely no idea about events, classes, inheritance, properties, and so on. You might have the most elegant code running inside your program, but the user will angrily point out that a button isn't centered on the form. Or you might commit the worst faux pas—a misspelled word on a menu! While good visual design can't rescue a program that crashes or runs like a drunk snail, it can give a professional first impression.

Examining the Handiwork of the IDE-Generated Code

The code required to wire up the controls we added to the form is taken care of by the IDE. Spend a few minutes reviewing the code highlighted below, which was added to the code generated for our form program in Chapter 1. Notice that all the new code was added in the Windows Form Designer generated code region. So, while you can see it, you don't have to be concerned with the code there. However, reviewing what this code does is instructive for when you want to write your own controls code. In the highlighted code, you will also start to see how objects are created and their properties set. Double-click the form to bring up the code.

Public Class frmTimeClass     Inherits System.Windows.Forms.Form #Region " Windows Form Designer generated code "     Public Sub New()         MyBase.New()         'This call is required by the         ' Windows Form Designer         InitializeComponent()         'Add any initialization after the         ' InitializeComponent() call     End Sub     'Form overrides dispose to clean up the component list     Protected Overloads Overrides _     Sub Dispose(ByVal disposing As Boolean)         If disposing Then             If Not (components Is Nothing) Then                 components.Dispose()             End If         End If         MyBase.Dispose(disposing)     End Sub     Friend WithEvents lblTime As System.Windows.Forms.Label     Friend WithEvents tiTimer As System.Windows.Forms.Timer     Friend WithEvents tIcon As System.Windows.Forms.NotifyIcon    Private components As System.ComponentModel.IContainer     'Required by the Windows Form Designer     'NOTE: The following procedure is required by the     ' Windows Form Designer.     'It can be modified using the Windows Form Designer.       'Do not modify it using the code editor.     <System.Diagnostics.DebuggerStepThrough()> _     Private Sub InitializeComponent()         Me.components = New System.ComponentModel.Container()         Dim resources As System.resources.ResourceManager = _             New System.resources.ResourceManager( _             GetType(frmTimeClass))         Me.lblTime = New System.Windows.Forms.Label()         Me.tiTimer = New System.Windows.Forms.Timer(Me.components)         Me.tIcon = _             New System.Windows.Forms.NotifyIcon(Me.components)         Me.SuspendLayout()         '         'lblTime         '         Me.lblTime.BackColor = System.Drawing.Color.Lime         Me.lblTime.BorderStyle = _             System.Windows.Forms.BorderStyle.Fixed3D         Me.lblTime.ForeColor = System.Drawing.Color.Blue         Me.lblTime.Location = New System.Drawing.Point(47, 21)         Me.lblTime.Name = "lblTime"         Me.lblTime.Size = New System.Drawing.Size(200, 23)         Me.lblTime.TabIndex = 0         '         'tiTimer         '         Me.tiTimer.Enabled = True         Me.tiTimer.Interval = 500         '         'tIcon         '         Me.tIcon.Icon = CType(resources.GetObject("tIcon.Icon"), _             System.Drawing.Icon)         Me.tIcon.Text = "VB .NET Time"         Me.tIcon.Visible = True         '         'frmTimeClass         '         Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)         Me.ClientSize = New System.Drawing.Size(294, 64)         Me.Controls.AddRange(New System.Windows.Forms.Control() _             {Me.lblTime})         Me.FormBorderStyle = _             System.Windows.Forms.FormBorderStyle.FixedDialog         Me.Icon = CType(resources.GetObject("$this.Icon"), _             System.Drawing.Icon)         Me.MaximizeBox = False         Me.MinimizeBox = False         Me.Name = "frmTimeClass"         Me.StartPosition = _             System.Windows.Forms.FormStartPosition.CenterScreen        Me.Text = "VB .NET Time"         Me.ResumeLayout(False)     End Sub #End Region End Class

To a classic Visual Basic programmer, this looks like an incredible amount of code for a program that doesn't do anything useful yet. But keep a couple of things in mind. First, you didn't write a single character in the editor yet, except to change the default name of the form class. Everything else has been provided for you by the IDE. Second, in classic Visual Basic programs, code like this was always present, but it was hidden from view. Visual Basic .NET simply provides access to code that was always there.

Examining the code the IDE inserted, you can see that our three controls were added. As I mentioned earlier, the controls live in the System.Windows.Forms namespace. If you've ever built objects in Visual Basic 6 that raised events, the WithEvents keyword is not new to you. It tells our class that the controls will be raising various events, such as the timer tick. The WithEvents keyword gives us access to any event in a control declared this way.

Friend WithEvents lblTime As System.Windows.Forms.Label Friend WithEvents tiTimer As System.Windows.Forms.Timer Friend WithEvents tIcon As System.Windows.Forms.NotifyIcon

Switch to the Forms Designer, display the Properties box, and click the drop-down list at the top of the box. As you can see in Figure 2-24, the fully qualified location of each of the controls is shown in the list. These locations match the namespaces in which the controls live. Not surprisingly, they are all found in the System.Windows.Forms namespace.

Figure 2-24

The controls on the form are part of the System.Windows.Forms namespace.

The next line that bears examination dimensions the Resource Manager. The ResourceManager class looks up culture-specific resources, provides resource fallback when a localized resource does not exist, and also supports resource serialization such as saving information to disk.

Dim resources As System.Resources.ResourceManager = _     New System.Resources.ResourceManager( _     GetType(frmTimeClass))

Almost every production-quality application needs to make use of resources. A resource is any nonexecutable data that is logically deployed with your application. The icons we added to the form and the notify icon are examples of resources. This data can be string literals, images, and persisted objects, among other items. As you know, the icon we used is stored as a binary file. Visual Basic .NET takes resource data and persists it in a separate resource file or sometimes in a designated section of a portable executable (PE) file. We used resource files in classic Visual Basic to store locale-dependent icons and strings. Likewise, you can create your own resource files in Visual Basic .NET. A resource file is a perfect vehicle for storing literal strings for menu choices in various languages, for example. You could have a resource file with menu strings in English and Spanish, and your program could then detect the current regional setting and use the correct strings. For now we are just storing an icon. The best part is that Visual Basic .NET takes on the responsibility of storing this information for you.

The rest of the new code is for setting control properties and storing icons. We changed the properties in the Properties box of the control, and the IDE wrote the changes to our code.

How Do We Hardwire the Controls?

You'll notice that neither the timer nor the notify icon have any code yet. Go back to the Designer and double-click each of the controls. The default events will then be added to your code.

Protected Sub tiTimer_Tick(ByVal sender As Object, _     ByVal e As System.EventArgs) End Sub Private Sub tIcon_Disposed(ByVal sender As System.Object, _     ByVal e As System.EventArgs) Handles tIcon.Disposed End Sub

Now you're ready to add some code to have the clock display the current date and time.

Can You Name That Namespace?

Remember that to use the prebuilt classes in the .NET common language runtime, you have to import their functionality. With classic Visual Basic, you would use built-in date methods to perform date manipulation and arithmetic. We will do much the same thing here, but because of the breadth of functionality, we will import only what we want.

The .NET Framework is built to be truly international. The framework's designers provided different formats for the way numbers, dates, and currency are rendered from country to country and culture to culture. They grouped this functionality in the System.Globalization namespace. This namespace contains information such as the language, the writing system, and the calendar used by various cultures. It also includes methods for common operations such as printing dates and sorting strings. In fact, to give you a sense of how specialized your programs can become, the Globalization namespace is where you would find the particulars of the Thai Buddhist Calendar Class.

Go ahead and add the Imports System.Globalization statement to your program as shown here:

Imports System.Globalization

Now that the date format information is visible to our module, we can take advantage of it. Add the following highlighted code to the tiTimer_Tick event handler.

Protected Sub tiTimer_Tick(ByVal sender As Object, _     ByVal e As System.EventArgs)     Dim dtDateTime As DateTime = Now()     Dim sMsgDate As String                  sMsgDate = dtDateTime.ToString("F")     lblTime.Text = sMsgDateEnd Sub

That's all the code you need. Let's take a look at what it does.

Date and Time Arithmetic

First, the timer is set to 500 milliseconds. This setting means that the Tick event of the tiTimer control will fire every one-half second. Each time it fires, the code in the event handler will execute. The code will grab the current system time and store it in the dtDateTime variable of the data type DateTime. You can see that we've used the new Visual Basic .NET feature that permits us to dimension and initialize a variable on the same line.

Dim dtDateTime As DateTime = Now()

In classic Visual Basic 6, a Date type is stored in a Double format using 4 bytes. In Visual Basic .NET, a Date uses the .NET Framework and common language runtime DateTime data type, which is an 8-byte integer value. The new DateTime object has a property named Ticks that stores the date and time as the number of 100-nanosecond intervals since 12:00 A.M. January 1, 1 A.D. (year) in the Gregorian calendar. The new DateTime object also has several helpful methods that permit you to determine whether one DateTime object is before, after, or equal to another DateTime object.

tip

Because of the different representations of dates in Visual Basic .NET, there is no implicit conversion between the Date and Double data types as in Visual Basic 6. If you have to convert between a Double and the Visual Basic 6 representation of Date, you can use the ToOADate and FromOADate methods of the DateTime class. However, if you are not converting older classic Visual Basic programs to Visual Basic .NET, you don't have to worry about this.

The Strings class is born knowing how to do all sorts of things related to dates. As you enter the code, IntelliSense will show all of the operations the code knows how to perform, as shown in Figure 2-25. We want to select the FormatDateTime method of the Strings class to format the date and time for presentation in our label control. We want the formatting to be applied every one-half second.

Figure 2-25

The Strings class has several formatting methods.

note

IntelliSense shows methods of objects with purple flying bricks. Properties are represented by a hand holding a card, presumably the value of the property is written on the card.

I'm aware that many of you are thinking that even with this trivial program, Visual Basic .NET appears to have an overwhelming number of cryptic options compared to classic Visual Basic. You might be thinking, "How would I know where to start looking for the .NET classes and their properties?"

After we work through more examples in the next few chapters, you'll begin to see how the options fit together. You'll understand exactly where to look for something and how to use it. But this familiarity comes only with practice. There is simply no other way. For now, I want you to become familiar with the power of our new environment. As you progress, you'll find that new vistas are open to you in your programming experience. As you learn your way around the functionality built into the .NET Framework, you'll find your productivity skyrocketing.

Formatting the Date and Time

We passed in the character F as the first parameter of the Format method. Listed in Table 2-6 are the format strings that you can choose from when displaying either the date, time, or date and time from a DateTime object. This table shows the characters to use in the first parameter to display the various built-in date patterns. Remember that we did all this with a single line of code.

sMsgDate = dtDateTime.ToString("F")

Sometimes, you might run into a situation in which you want to display the date or time in a custom format. Using a custom format poses no problem for Visual Basic .NET. You can use one of the characters or combination of characters listed in Table 2-7 to create a format that fits your requirements. Be sure to enclose the character or characters in quotation marks ("").

Table 2-6  The Built-In Date and Time Formats Available in Visual Basic .NET

Format Character

Resulting Format Pattern

D

MM/dd/yyyy

D

dddd, MMMM dd, yyyy

F

dddd, MMMM dd, yyyy HH:mm

F (the one we used)

dddd, MMMM dd, yyyy HH:mm:ss

G

MM/dd/yyyy HH:mm

G

MM/dd/yyyy HH:mm:ss

m, M

MMMM dd

r, R

ddd, dd MMM yyyy HH':mm':'ss 'GMT'

S

yyyy-MM-dd HH:mm:ss

T

HH:mm

T

HH:mm:ss

U

yyyy-MM-dd HH:mm:ss

U

dddd, MMMM dd, yyyy HH:mm:ss

y, Y

MMMM, yyyy

Table 2-7  Characters to Use to Create a Custom Date and Time Format

Format Pattern

Description

d

The day of the month. Single-digit days will not have a leading zero.

dd

The day of the month. Single-digit days will have a leading zero.

ddd

The abbreviated name of the day of the week.

dddd

The full name of the day of the week.

M

The numeric month. Single-digit months will not have a leading zero.

MM

The numeric month. Single-digit months will have a leading zero.

MMM

The abbreviated name of the month.

MMMM

The full name of the month.

y

The year without the century. If the year without the century is less than 10, the year is displayed with no leading zero.

yy

The year without the century. If the year without the century is less than 10, the year is displayed with a leading zero.

yyyy

The year including the century in four digits.

h

The hour in a 12-hour clock. Single-digit hours will not have a leading zero.

hh

The hour in a 12-hour clock. Single-digit hours will have a leading zero.

H

The hour in a 24-hour clock. Single-digit hours will not have a leading zero.

HH

The hour in a 24-hour clock. Single-digit hours will have a leading zero.

m

The minute. Single-digit minutes will not have a leading zero.

mm

The minute. Single-digit minutes will have a leading zero.

S

The second. Single-digit seconds will not have a leading zero.

ss

The second. Single-digit seconds will have a leading zero.

T

The first character in the A.M./P.M. designator.

tt

The A.M./P.M. designator.

z

The time zone offset (hour only). Single-digit hours will not have a leading zero.

zz

The time zone offset (hour only). Single-digit hours will have a leading zero.

zzz

The full time zone offset (hour and minutes). Single-digit hours and minutes will have leading zeros.

:

The default time separator.

/

The default date separator.

% c

Where c is a standard format character. Displays the standard format pattern associated with the format character.

\ c

Where c is any character. Displays the character literally.

Let's Run This Baby!

Choose Debug | Start, or simply press F5. You'll see the Solution Builder telling you it's building the program. The build should succeed, as shown in Figure 2-26. Because we are not deploying our program yet, all indicators are 0. We're ready for liftoff.

Figure 2-26

A successful build.

You should see the loading sequence of the assemblies used in our program displayed in the Output window, shown in Figure 2-27. The .NET run-time library, Mscorlib.dll, is loaded, then the executable, and finally the respective assemblies needed to run our code.

Figure 2-27

The assemblies needed to run VB .NET Clock.

If everything goes according to plan, you'll see the clock in the center of the screen, as shown in Figure 2-28. The user can't resize it but can only dismiss it by using the Close button. The time is updated twice a second.

Figure 2-28

The VB .NET Time program in action.

Also notice the notify icon at the far right side of the taskbar, shown in Figure 2-29. If you let your mouse hover over it for a second, the tooltip will pop up telling you that an instance of the VB .NET Time program is running. Not too shabby for setting a few properties and writing a few lines of code.

Figure 2-29

VB .NET Time's notify icon in the taskbar.

Since you've gone through this explanation about what's happening, why not spend a few minutes experimenting with the methods that display various custom date and time formats. Personally, I prefer a 12-hour clock with an A.M./P.M. designator. Simple enough. Modify the format method of the dtDateTime object as follows and rerun the program.

sMsgDate = dtDateTime.ToString("hh:mm:ss tt")

This format will provide the current system time in 12-hour format, as shown in Figure 2-30.

Figure 2-30

VB .NET Time showing the time in 12-hour format.

Except for the single Import statement, all the functionality is sandwiched between Class and End Class statements. Visual Basic .NET is all about classes.

Public Class frmTimeClass  End Class



Coding Techniques for Microsoft Visual Basic. NET
Coding Techniques for Microsoft Visual Basic .NET
ISBN: 0735612544
EAN: 2147483647
Year: 2002
Pages: 123
Authors: John Connell

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