Home > Articles > Programming > Windows Programming

This chapter is from the book

The Project

Welcome to the Project section, the part of each chapter where you have an opportunity to get "hands on" with Visual Studio 2005 and Visual Basic. Development of the Library project, the main project focus of this book, formally begins in Chapter 3, "Introducing the Project," but there's still project work to do in the meantime. In this chapter, I'll introduce you to the sample source code provided with this book, and we'll take a stab at using it.

Because most Project sections, including this one, will involve Visual Studio, make sure you have it installed and ready to use. Also, because each Project section is designed for you to use interactively with the supplied source code, I will assume that you have downloaded and installed the source code (see Appendix A, "Installing the Software," for instructions), and are viewing the source code with one eye while you read this section with the other. I will print sections of the source code in the book, but with tens of thousands of source code lines in the Library project, I will not be able to print every line here. You will certainly get a lot out of each Project section by simply reading them, but you will get even more if you have access to the full source code.

In this chapter's project, we'll load a sample program into Visual Studio and run it. There are two ways to do this. The first way is just to open the existing project directly from the installation directory. Browse to the directory where you installed this book's source code, open the "Chapter 1" subdirectory, and double-click the Chapter1.vbproj file. This will open the project directly in Visual Studio, ready to use.

The second way is to use the chapter-specific project templates to create new projects in Visual Studio. The Setup program for this book's source code modified your installation of Visual Studio, adding new entries in the New Project dialog window. Each of these new "project templates" can be used as the starting point for a new Visual Basic project. To load the Chapter 1 sample program using the template, start Visual Studio. The Start Page will appear, as shown way back in Figure 1-6. From the File menu, select New Project to display the New Project dialog box (see Figure 1-9).

Figure 1-9

Figure 1-9 The New Project dialog box—so many choices

Your New Project dialog box may differ slightly depending on the features you chose to install with Visual Studio. The available projects are grouped by the description in the Project types field. For instance, Figure 1-9 shows the various default project types you can create in Visual Basic, including Windows Applications (standard desktop applications for the Windows platform, Class Libraries (a DLL of class-defined features), and Console Applications (command-line text-based applications). To create a new application, first select the project type, select the Template to use, and finally enter the name of the new project in the Name field. Clicking the OK button creates a new project.

To use the sample Chapter 1 project, select the Start-to-Finish Visual Basic 2005 entry within the Visual Basic project type, and then select Chapter 1 Sample from the Template field (see Figure 1-10). Finally, click OK to create the new sample project.

Figure 1-10

Figure 1-10 Selecting the Chapter 1 Sample project

Once the project loads, access the program's main form by double-clicking on the Form1.vb file in the Solution Explorer (see Figure 1-11).

Figure 1-11

Figure 1-11 The main form of the sample application

This default presentation of Visual Studio Professional Edition includes three editing components: (1) the main editing area, where the view of "Form1" appears; (2) the Solution Explorer panel, which provides access to all files included in the project; and (3) the Properties panel, which lets you edit various aspects of the currently selected item in the main editor area or elsewhere in the user interface.

The sample project is pretty basic. It includes one form with a single action button. Clicking this button in the running application displays a simple message. Run the project by pressing the F5 key. When the main form appears, clicking on the Go Ahead, Click Me button to display the message in Figure 1-12 (goal, sweet goal).

Figure 1-12

Figure 1-12 Hello again, world!

So, how about all of that complex code I had to write to develop this multifaceted application? It's all there for the viewing. From the Solution Explorer panel, right-click on the Form1.vb entry, and select View Code from the shortcut menu. (As with most source code samples presented in this book, I have had to slightly adjust the code so that it displays properly on the printed page. Generally, this involves splitting a long logical line into two or more shorter ones.)

Public Class Form1
   Private Sub Button1_Click(ByVal sender As System.Object, _
         ByVal e As System.EventArgs) Handles Button1.Click
      MsgBox("Hello, World!")
   End Sub
End Class

We'll get into the intricacies of such code in later chapters, but here is the gist.

  • The main form, Form1, is represented in code by a class, named Form1.
  • The form includes a command button named Button1 that exposes a Click event. This event is handled by the Button1_Click procedure, a member of the Form1 class.
  • The "event handler," Button1_Click, includes a single statement, a "MsgBox" statement. This statement does the heavy lifting by presenting the ever-friendly message box to the world.

That's all of the code that I wrote for Form1.vb. It sure seems pretty short for all the work it does. There has to be more code hiding somewhere. And sure enough, there are actually half-a-dozen or so more files included in the project. Visual Studio hides these by default, since it manages some or all of the content in these files on your behalf. To view the files, click on the Show All Files button (the second toolbar button from the left in the Solution Explorer panel). Look at all those files! To see the additional files associated with Form1, expand it by clicking on the plus sign to its left (see Figure 1-13).

Figure 1-13

Figure 1-13 Viewing hidden files through the Solution Explorer

Double-click on the Form1.Designer.vb entry to see the code that Visual Studio automatically wrote for this form. (Dramatic pause.) Wow! Look at all of that scary code. Actually, it's not that bad. By the end of this book, you will have a firm grasp on all of it. Here in Chapter 1, it's not really necessary to comprehend it all, but there are a few interesting lines to note. I'm including line numbers to make it easier to find the matching code in Visual Studio. If you want to view line numbers in Visual Studio (Professional Edition instructions listed here):

  1. Select the Tools snippet.jpg Options menu item to display Visual Studio's options.
  2. Select Text Editor snippet.jpg Basic snippet.jpg Editor from the tree-view to the left. If the Show all settings field is checked, the last component in the tree-view will be General, not Editor.
  3. Select (check) the Line Numbers field on the right.
  4. Click OK to apply the changes.

If you're new to Visual Basic or .NET programming, don't worry now if all this code doesn't make sense; it will all become clear as you pass through the pages of this book.

 
 1 <Global.Microsoft.VisualBasic.CompilerServices. _
      DesignerGenerated()> _
 2 Partial Public Class Form1

20 <System.Diagnostics.DebuggerNonUserCode()> _
21 Protected Overloads Overrides Sub Dispose _
      (ByVal disposing As Boolean)

These lines show attributes in action. These two attributes (DesignerGenerated and DebuggerNonUserCode) are somewhat like the Obsolete attribute discussed earlier, in that they provide some informational identity to the related code. DesignerGenerated modifies the entire section of Form1's code, while DebuggerNonUserCode only modifies the Dispose member. For clarity, both attributes include their full namespace paths. The Global keyword at the beginning of the DesignerGenerated attribute is actually a Visual Basic keyword that says, "Start at the very tippy-top of the namespace hierarchy; this is not a relative path."

2 Partial Public Class Form1

Did you see the word Partial right there on line 2? I know I did. Hey, wait a minute; "Public Class Form1" also appeared in the Form1.vb file, but without the Partial keyword. Visual Basic 2005 includes a new feature that lets you divide a single class (Form1 in this case) among multiple source code files by including the Partial keyword with at least one of the parts. Pretty cool, eh? It allows Visual Studio to add complex initialization code for your form (as found in this Form1.Designer.vb file) without it bothering your main source code file (Form1.vb).

3 Inherits System.Windows.Forms.Form

The Inherits keyword defines the inheritance relationship between this new Form1 class and the previously written System.Windows.Forms. Form class. Form is the "base" class, while Form1 is the "derived" class; Form1 inherits all of the functionality of the Form class, including its initial look and feel. I'll discuss these class relationships in more detail in Chapter 8.

44 Friend WithEvents Button1 As System.Windows.Forms.Button

Line 44 defines the Go Ahead, Click Me button that appears in the center of the form. All controls that appear on your form are separate instances of classes. (Friend is a declaration statement described in the next chapter.) The WithEvents keyword indicates that this instance of the Button class will respond to events, such as a user clicking on it with the mouse. This line doesn't actually create an instance of the Button class; that happens back on line 22.

22 Me.Button1 = New System.Windows.Forms.Button

The New keyword creates new instances of classes. In this case, that new instance is assigned to the Button1 class member defined on line 44. At this moment, Button1 is a default instance of the Button class; it doesn't have any of its custom settings, such as its size and position, or the Go Ahead, Click Me display text. All of that is set in lines 27 to 31.

27 Me.Button1.Location = New System.Drawing.Point(64, 104)
28 Me.Button1.Name = "Button1"
29 Me.Button1.Size = New System.Drawing.Size(152, 23)
30 Me.Button1.TabIndex = 0
31 Me.Button1.Text = "Go Ahead, Click Me!"

Finally, the button is "glued" onto the form on line 38.

38 Me.Controls.Add(Me.Button1)

This adds the Button1 instance to the list of Controls managed by Form1. The Me keyword used throughout this code refers to the Form1 class itself, so Me.Button1 refers to the Button1 class member specifically in the current Form1 class.

Most of the code in this file appears in the InitializeComponent member procedure.

21 Private Sub InitializeComponent()
      ...
43 End Sub

When Visual Basic creates an instance of Form1 to display on the screen, it calls the InitializeComponent procedure to do the work of adding the controls to the form. Actually, Visual Basic calls the form's constructor, which in turn calls InitializeComponent. Constructors are special class members that perform any needed initialization on a class instance. They are called automatically by .NET each time a class instance is created. In Visual Basic, all constructors use the name New, as with the following code:

Friend Class ClassWithConstructor
   Public Sub New()
      ' ----- All initialization code goes here.
   End Sub
End Class

I'll talk much more about constructors in Chapter 8, but for now, locate the constructor in the code for Form1. (Very long pause.) What? There is no constructor? So, if there isn't a constructor, how is the InitializeComponent member ever called?

That's what I'd like to know. Actually, when the Visual Basic compiler generates the IL code for Form1, it adds a constructor silently, a constructor that calls InitializeComponent. How about that! Why didn't Microsoft simply include the constructor's code right in the source code? It's a simplicity-for-the-programmer thing. They needed to have a default constructor that would call InitializeComponent, but they didn't want a conflict to arise if you added your own default constructor in the non-Designer file. So they hid all of the code until it came time to actually compile the form. Clearly, it's all rather hush-hush, so let's move on.

Well, that's pretty much the entire code, at least the part that matters to us now. Although we will rarely, if ever, examine the Visual Studio-generated code for the forms in the Library project, it's good to see what's going on behind the scenes. If you were a Visual Basic 6 programmer, you probably looked at the source code for your forms through Notepad at one time or another. If you did, you noticed that the form and all of its controls were defined with a hierarchy of special commands, and not with actual Visual Basic code. In .NET, that's all changed; the form and all of its controls are created with ordinary Visual Basic code, so you can access it all and see what is really going on.

Now, turn to Chapter 2, "Introducing Visual Basic," where I delve into the Visual Basic language itself.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020