Home > Articles > Programming > Windows Programming

This chapter is from the book

3.16 Introduction to Windows Application Programming

Today, users demand software with rich graphical user interfaces (GUIs) that allow them to click buttons, select items from menus and much more. In this chapter and the previous one, we have created console applications. However, the vast majority of Visual Basic programs used in industry are Windows applications with GUIs. For this reason, we have chosen to introduce Windows applications early in the book, although doing so exposes some concepts that cannot be explained fully until later chapters.

In Chapter 2, we introduced the concept of visual programming, which allows programmers to create GUIs without writing any program code. In this section, we combine visual programming with the conventional programming techniques introduced in this chapter and the previous chapter. Through this combination, we can enhance considerably the Windows application introduced in Chapter 2.

Before proceeding, load the project ASimpleProgram from Chapter 2 into the IDE, and change the (Name) properties of the form, label and picture box to FrmASim-pleProgram, lblWelcome and picBug, respectively. The modification of these names enables us easily to identify the form and its controls in the program code. [Note: In this section, we change the file name from Form1.vb to ASimpleProgram.vb, to enhance clarity.]

Good Programming Practice 3.2

The prefixes Frm, lbl and pic allow forms, labels and picture boxes; respectively, easily to be identified easily in program code.

With visual programming, the IDE generates the program code that creates the GUI. This code contains instructions for creating the form and every control on it. Unlike with a console application, a Windows application's program code is not displayed initially in the editor window. Once the program's project (e.g., ASimpleProgram) is opened in the IDE, the program code can be viewed by selecting View > Code. Figure 3.16 shows the code editor displaying the program code.

Figure 3.16Fig. 3.16 DE showing code for the program inI Fig. 2.14.

Notice that no module is present. Instead, Windows applications use classes. We already have seen examples of classes, such as Console and MessageBox, which are defined within the .NET Framework Class Library (FCL). Like modules, classes are logical groupings of procedures and data that simplify program organization. Modules are discussed in detail in Chapter 4, Procedures. In-depth coverage of classes is provided in Chapter 5, Object-Based Programming.

Every Windows application consists of at least one class that Inherits from class Form (which represents a form) in the FCL's System.Windows.Forms namespace. The keyword Class begins a class definition and is followed immediately by the class name (FrmASimpleProgram). Recall that the form's name is set by means of the (Name) property. Keyword Inherits indicates that the class FrmASimplePro-gram inherits existing pieces from another class. The class from which FrmASimpleProgram inherits—here, System.Win-dows.Forms.Form—appears to the right of the Inherits keyword. In this inheritance relationship, Form is called the superclass, or base class, and FrmASimpleProgram is called the subclass, or derived class. The use of inheritance results in a FrmASimpleProgram class definition that has the attributes (data) and behaviors (methods) of class Form. We discuss the significance of the keyword Public in Chapter 5.

A key benefit of inheriting from class Form is that someone else previously has defined "what it means to be a form." The Windows operating system expects every window (e.g., a form) to have certain capabilities (attributes and behaviors). However, because class Form already provides those capabilities, programmers do not need to "reinvent the wheel" by defining all those capabilities themselves. In fact, class Form has over 400 methods! In our programs up to this point, we have used only one method (i.e., Main), so you can imagine how much work went into creating class Form. The use of Inherits to extend from class Form enables programmers to create forms quickly and easily.

In the editor window (Fig. 3.16), notice the text WindowsFormDesignergen-eratedcode, which is colored gray and has a plus box next to it. The plus box indicates that this section of code is collapsed. Although collapsed code is not visible, it is still part of the program. Code collapsing allows programmers to hide code in the editor, so that they can focus on key code segments. Notice that the entire class definition also can be collapsed, by clicking the minus box to the left of Public. In Fig 3.16, the description to the right of the plus box indicates that the collapsed code was created by the Windows Form Designer (i.e., the part of the IDE that creates the code for the GUI). This collapsed code contains the code created by the IDE for the form and its controls, as well as code that enables the program to run. Click the plus box to view the code.

Upon initial inspection, the expanded code (Fig. 3.17) appears complex.This code is created by the IDE and normally is not edited by the programmer. However, we feel that it is important for readers to see the code that is generated by the IDE, even though much of the code is not explained until later in the book. This type of code is present in every Windows application. Allowing the IDE to create this code saves the programmer considerable development time. If the IDE did not provide the code, the programmer would have to write it, which would require a considerable amount of time. The vast majority of the code shown has not been introduced yet, so you are not expected to understand how it works. However, certain programming constructs, such as comments and control structures, should be familiar. Our explanation of this code will enable us to discuss visual programming in greater detail. As you continue to study Visual Basic, especially in Chapters 5–10, the purpose of this code will become clearer.

Figure 3.17Fig. 3.17 Windows Form Designer-generated code when expanded.


When we created this application in Chapter 2, we used the Properties window to set properties for the form, label and picture box. Once a property was set, the form or control was updated immediately. Forms and controls contain a set of default properties, which are displayed initially in the Properties window when a form or control is created. These default properties provide the initial characteristics of a form or control when it is created. When a control, such as a label, is placed on the form, the IDE adds code to the class (e.g., FrmASimpleProgram) that creates the control and that sets some of the control's property values, such as the name of the control and its location on the form. Figure 3.18 shows a portion of the code generated by the IDE for setting the label's (i.e., lblWelcome's) properties, including the label's Font, Location, Name, Text and TextAlign properties. Recall from Chapter 2 that we explicitly set values for the label's Text and Tex-tAlign properties. Other properties, such as Location, are set only when the label is placed on the form.

Figure 3.18Fig. 3.18 Code generated by the IDE for lblWelcome.

The values assigned to the properties are based on the values in the Properties window. We now demonstrate how the IDE updates the Windows Form Designer–generated code created when a property value in the Properties window changes. During this process, we must switch between code view and design view. To switch views, select the corresponding tabs: ASimpleProgram.vb for code view and ASimpleProgram.vb [Design] for design view. Alternatively, you can select View > Code or View > Designer. Perform the following steps:

  1. Modify the file name. First, change the name of the file from Form1.vb to ASimpleProgram.vb by clicking the file name in the Solution Explorer and changing the File Nameproperty.

  2. Modify the label control's Textproperty, using the Properties window. Recall that properties can be changed in design view by clicking a form or control to select it and modifying the appropriate property in the Properties window. Change the Text property of the label to "DeitelandAssociates" (Fig. 3.19).

    Figure 3.19Fig. 3.19 Properties window as used to set a property value.

  3. Examine the changes in code view. Switch to code view, and examine the code. Notice that the label's Textproperty is now assigned the text that we entered in the Properties window (Fig. 3.20). When a property is changed in design mode, the Windows Form Designer updates the appropriate line of code in the class to reflect the new value.

    Figure 3.20Fig. 3.20 Windows Form Designer-generated code reflecting new property values.

  4. Modify a property value in code view. In the code-view editor, locate the three lines of comments indicating the initialization for lblWelcome, and change the Stringassigned to Me.lblWelcome.Textfrom "Deitel andAssoci-ates" to "VisualBasic.NET" (Fig. 3.21).Then switch to design mode. The label now displays the updated text, and the Properties window for lblWel-comedisplays the new Textvalue (Fig. 3.22).

    Note

    Property values should not be set using the techniques presented in this step. Here, we modify the property value in the IDE-generated code only as a demonstration of the relationship between program code and the Windows Form Designer.

    Figure 3.21 Fig. 3.21 Changing a property in the code-view editor.


    Figure 3.22 Fig. 3.22 New Text property value as reflected in design mode.

  5. Change the label's Textproperty at runtime. In the previous steps, we set properties at design time. Often, however, it is necessary to modify a property while a program is running. For example, to display the result of a calculation, a label's text can be assigned a Stringcontaining the result. In console applications, such code is located in Main. In Windows applications, we must create a method that executes when the form is loaded into memory during program execution. Like Main, this method is invoked when the program is run. Double-clicking the form in design view adds a method named FrmASimpleProgram_Load to the class (Fig. 3.23). Notice that FrmASimpleProgram_Loadis not part of the Windows Form Designer-generated code. Add the statement lblWelcome.Text="Vi-sualBasic"into the body of the method definition (Fig. 3.24). In Visual Basic, properties are accessed by placing the property name (i.e., Textin this case) after the class name (i.e., lblWelcomein this case), separated by the dot operator. This syntax is similar to that used when accessing class methods. Notice that the Intel-liSense feature displays the Textproperty in the member list after the class name and dot operator have been typed (Fig. 3.23). In Chapter 5, Object-Based Programming, we discuss how programmers can create their own properties.

    Figure 3.23 Fig. 3.23 Adding program code to FrmASimpleProgram_Load.


    Figure 3.24 Fig. 3.24 Method FrmASimpleProgram_Load containing program code.

  6. Examine the results of the FrmASimpleProgram_Load method. Notice that the text in the label looks the same in Design mode as it did in Fig. 3.22. Note also that the Property window still displays the value "VisualBasic.NET" as the label's Textproperty. The IDE-generated code has not changed either. Select Build > Build Solution and Debug > Start to run the program. Once the form is displayed, the text in the label reflects the property assignment in FrmASimpleProgram_Load(Fig. 3.25).

    Figure 3.25 Fig. 3.25 Changing a property value at runtime.

  7. Terminate program execution. Click the close button to terminate program execution. Once again, notice that both the label and the label's Textproperty contain the text Visual Basic .NET. The IDE-generated code also contains the text VisualBasic.NET, which is assigned to the label's Textproperty.

This chapter discussed how to compose programs from control structures that contain actions and decisions. In Chapter 4, Procedures and Arrays, we introduce another program-structuring unit, called the procedure. We will discuss how to compose programs by combining procedures that are composed of control structures. We also discuss how procedures promote software reusability. In Chapter 5, Object-Based Programming, we discuss in more detail another Visual Basic program-structuring unit, called the class. We then create objects from classes and proceed with our treatment of object-oriented programming—a key focus of this book.

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