Home > Articles > Certification > Microsoft Certification

Writing Windows Forms Applications in Visual Studio .NET 2003

By using the tools and controls in Visual Studio .NET, learn how to write user-friendly Windows Forms by exploring forms, controls, events, and inheritance.
This chapter is from the book

For more information on .NET, visit our .NET Reference Guide or sign up for our .NET Newsletter.

The ability to rapidly develop and deploy forms-based applications is what led to the phenomenal success of Visual Basic. Visual Basic enables you to build enterprise-level applications at lightning speed without requiring you to fully understand what the underlying infrastructure of the operating system is doing. With .NET, this ability is taken to the next level. The Windows Forms model for .NET is fully integrated into the .NET Framework. The development model is fully object oriented, enabling you to create better applications faster using Visual Studio .NET. The rapid in Rapid Application Development (RAD) has never been truer when developing with Windows Forms. Today, you learn about

  • Using forms and controls

  • How to handle events in Windows Forms

  • Adding controls to forms

  • Dynamically adding controls to Forms

  • Creating MDI applications with Windows Forms

  • Inheriting Windows Forms

  • Using common dialogs in Windows Forms

Hello .NET!

Every introduction to writing applications needs to start with the Hello World type application. This isn't because it's such a cool cliché. It's to get you familiar with the environment you're working in and to better explain what's going on when you're running the application. To get you started with Visual Studio .NET development, you're going to create the HelloNET application.

To begin, start Visual Studio .NET. On the Getting Started page, click the New Project button. You're prompted with the New Project dialog you learned about yesterday. Figure 3.1 demonstrates the New Project dialog.

Figure 3.1Figure 3.1 The New Project dialog box.

Select the Windows Application template from either the C# or Visual Basic folder, and change the Name to HelloNET. Click the OK button to create the application.

After the project has been created, you should be looking at something like Figure 3.2.

NOTE

Throughout this book, there are code examples for Visual Basic .NET and C# for everything you learn. When I ask you to create a new application, most of the time I say to call it something_vb or something_cs, depending on the language you're writing your code in. To differentiate the code in the downloads for the book and to enable you to write the same application in both languages, you can't have the same project name. So, if there are screenshots that look like a project name is different from what I ask you to create, that's the reason. By the end of the book, you'll see there's very little difference between C# and Visual Basic .NET, and you'll be bilingual!

Figure 3.2Figure 3.2 The HelloNET application.

As you learned yesterday, there are many useful windows when developing applications. The key items you'll use when creating Windows Forms applications are the Solution Explorer, the Properties window, and the Toolbox. If you don't see these windows on your screen, you can get to them in the ways shown in Table 3.1.

Table 3.1 Shortcuts to Main Windows When Designing Forms

Window

Shortcut Options

Properties

F4 key

View, Properties from the View menu

The Properties button on the standard toolbar

Toolbox

Ctrl+Alt+X shortcut keys

View, Toolbox from the View menu

The Toolbox button on the standard toolbar

Solution Explorer

Ctrl+Alt+L shortcut keys

View, Solution Explorer from the View menu

The Solution Explorer button on the standard toolbar


The key to rapid development with Windows Forms is the ability to easily drag items from the Toolbox onto the forms, set properties on the controls that you add using the Properties window, and write code that responds to the controls and form events. That's why the three windows in Table 3.1 are so important.

Next, you must add some controls to the form. From the Toolbox, drag a Button control, Textbox control, and Label control to the form that's in the Windows Forms designer. Your form should look something like Figure 3.3 after the controls are added.

TIP

There are a couple of other ways to add controls to a form. First, you can double-click Toolbox controls to add them to a form. They are added on top of the last control added to the form. The second way is to select a control from the Toolbox and "draw" it onto the form with your mouse. This will let you position and size the control as you add it to the form.

Figure 3.3Figure 3.3 Adding controls to the default form.

Next, single-click the form and press the F4 key to view its properties. Change the following properties on the form:

  • StartPosition: CenterScreen

  • MaximumSize: 400, 400

  • MinimumSize: 200, 200

  • Font: Tahoma, 14pt

After you set the Font property, notice that the font sizes of the controls on the form change to the form's font properties. This is a new feature in Windows Forms; the controls inherit the font properties of the form. You can easily override these properties by setting properties on the individual controls. You learn more about the different controls a little later.

Next, double-click Button1 to get to the Code Editor window. This works like Visual Basic 6 did: You double-click controls and you're taken to their default event.

You're now looking at the Form_Load event. Notice that the load event accepts two arguments—System.Object and System.EventArgs—as the following code snippet demonstrates:

VB.NET

Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

C#

    private void Form1_Load(object sender, System.EventArgs e)
    {

    }

Every control that you add to a form (and the form itself) always has to accept the object that's passing it the data and then the event arguments for that object. Depending on the control and the event, it won't always be System.EventArgs, but there will always be an event arguments parameter.

In the Form_Load event, add the code in Listing 3.1, which displays a message box welcoming you to Visual Studio .NET.

Listing 3.1 The Form_Load Event Code for HelloNET

VB.NET

Private Sub Form1_Load(ByVal sender As System.Object, _
        ByVal e As System.EventArgs) Handles MyBase.Load

  MessageBox.Show("Welcome to .NET!")

End Sub

C#

private void Form1_Load(object sender, System.EventArgs e)
{
  MessageBox.Show("Welcome to .NET!");
}

You'll notice that the MessageBox class is used to prompt information back to the user. The functionality of the MessageBox class is very similar to that of the MsgBox function in Visual Basic 6. You can pass a prompt, respond to button events, and set the title for the message box that's displayed.

Next, you need to add code for the click event of the Button you added to the form earlier. There are several ways to write code that responds to events in Windows Forms. The easiest way to write code for an event is to double-click a control on the Forms Designer and you're taken to the default event for that control in the Code Editor.

If you're writing in Visual Basic, you can select the control from the Class Name drop-down list in the upper-left corner of the Code Editor. After you select the control you want to write an event for, you can select the correct method from the Method Name drop-down list, which is next to the Class Name drop-down list. Figure 3.4 demonstrates the Method Name drop-down list for some of the Button1 events. Notice that Button1 was selected from the Class Name list.

Figure 3.4Figure 3.4 The Button1 Method Name options.

You'll also notice the (Overrides) and (Base Class Events) options in the Class Name drop-down. The (Overrides) option gives you all the methods, properties, and events that you can programmatically override for the form. The (Base Class Events) option gives you the methods for the Form class. A little later today you'll better understand how classes work and what they'll mean to you as you develop not only in Windows Forms, but also in .NET as a whole.

If you're a C# developer, you don't have the Class Name and Method Name drop-down lists in the Code Editor for events that haven't been added to the form. To add new events for the form and for controls on the form, you must select the control on the form while you're in the Forms Designer. Then, on the toolbar of the Properties window for the selected control, click the lightning bolt button, which gives you the list of events for the selected control. When you find the event you want to write code for, you can double-click the event name in the list, and you're taken to the Code Editor for that event. Figure 3.5 demonstrates the button1_Click event selected in the Properties window.

Figure 3.5Figure 3.5 The button1_Click event of the Properties window for a C# application.

Now that you know how to add events with the IDE, add the code in Listing 3.2 to the button1_Click event.

Listing 3.2 button1_Click Event for the HelloNET Application

VB.NET

Private Sub Button1_Click(ByVal sender As Object, _
      ByVal e As System.EventArgs) Handles Button1.Click

  Label1.Text = TextBox1.Text

End Sub

C#

private void button1_Click(object sender, System.EventArgs e)
{
  label1.Text = textBox1.Text;
}

There are a few items to note on the code you just wrote:

  • The Text property is used for both the Label and the TextBox control. This is different from Visual Basic 6. There is no longer a Caption property for labels, forms, or other controls—it's replaced with the Text property.

  • C# is a case-sensitive language, and the casing defaults to camel casing, meaning that the first character of an object name is lowercase and the first letters of any subsequent concatenated words are uppercase. Visual Basic uses Pascal casing, meaning that the first character is uppercase and the first letters of any subsequent concatenated words are uppercase.

  • Visual Basic automatically fixes the casing of object names, but C# does not. This also means the auto-list members do not work in C# if the casing isn't correct. Figure 3.6 demonstrates auto-list members in C# when the casing is correct. Auto-list members works in Visual Basic even if the casing is incorrect.

Figure 3.6Figure 3.6 Auto-list members in the C# Code Editor.

Now that the code has been added and you're getting an idea of how to work with the IDE, press the F5 button to run the application. Pressing F5 has the same effect as selecting Start from the Debug menu or clicking the Start button on the Standard toolbar.

When the application starts, you're prompted with Welcome to .NET! that you added in the Form_Load event. After the form is active, type Hello .NET into the TextBox and click the Button on the form. The Label control is filled with the contents of the TextBox.

You also set some properties in the form, such as MinimumSize, MaximumSize, AutoScroll, and StartPosition. When the application starts, the form shows up in the middle of the screen. If you now resize the form, you'll see that it can only grow to a certain size and shrink to a certain size. This is a cool feature that wasn't in Visual Basic 6. The bigger-than-life feature is AutoScroll. If you resize the form and the controls can't remain visible, scrollbars appear automatically. Figure 3.7 demonstrates AutoScroll in action.

Figure 3.7Figure 3.7 The AutoScroll property for a form in action.

You can click the X in the upper-right of the form to close the form and get back to the designer.

NOTE

When you're in the integrated development environment (IDE) and press the F5 key to run the application, you're in Debug mode. In Debug mode, the application is running and you have access to all the debugging features in Visual Studio .NET that you learn about on Day 7, "Exceptions, Debugging, and Tracing." When you stop debugging, by closing the main form that is running or clicking the Stop button on the Debug toolbar, you go back to Design time. So, when you're writing an application in the Visual Studio .NET IDE, you're either in Debug mode or Design time mode. When the application is compiled and you run it from the file system, it's called runtime.

The AutoScroll property is one of many cool properties that forms and controls have in .NET. To see some of the new properties, follow Table 3.2 and change the corresponding properties.

Table 3.2 Properties to Change on the Form1 Controls

Control

Property

Value

Form1

Name

frmMain

Opacity

80%

FormBorderStyle

SizeableToolWindow

SizeGripStyle

Auto

Text

Wow This Is Great!

TopMost

True

Button1

Anchor

Top, Left, Right

Cursor

Hand

FlatStyle

Flat

BackColor

SteelBlue

Text

Click Me!

ForeColor

LightGray

Name

ClickMe

Label1

Dock

Bottom

TextAlign

BottomRight

Textbox1

CharacterCasing

Upper

MultiLine

True

AcceptsReturn

300,300

Anchor

Top, Bottom, Left, Right

Size

292, 140

Location

28, 68

TextAlign

Right

Cursor

Cross


After you've changed the properties for the controls, press the F5 key to run the application. Figure 3.8 shows the form after typing some text in the box and resizing the form.

Figure 3.8Figure 3.8 Running the HelloNET application after changing object properties.

You'll notice some very cool things happening with this form:

  • It is almost invisible. The Opacity property can be set anywhere from 0% to 100%, which makes the forms see-through. When the TransparencyKey property on the form is set, all controls that contain the color set in the TransparencyKey are 100% transparent. Try it out!

  • Setting the Dock property on the Label control glues it to the bottom of the form. All controls can be docked in Windows Forms.

  • Setting the Anchor property automatically resizes the control when the form is resized. This is automatic, and every control in Windows Forms can be anchored. No more resize code!

  • The ScrollBars are no longer there. Because the Anchor and Dock properties are set on the form, there's no need to scroll—the controls always resize within the bound of the form.

  • The Cursor property is easily changed for all controls in Windows Forms. This enables you to customize the look and feel for each control when the mouse hovers over it.

  • The text in the Textbox is UPPERCASE, and the words display from right to left. You can use the Enter key inside the Textbox. Setting the CharacterCasing, AcceptsReturn, and TextAlign properties allow complete customization of the Textbox control.

  • The form stays on top of all other open applications. Using this property in conjunction with the Opacity property can give you some great options for always-open, nonintrusive applications.

Besides making a form that has no real use, the goal of setting the properties for the controls on the form was to introduce you to some of the cooler features of Windows Forms. When you changed properties such as Anchor, Dock, Cursor, and TextAlign, you learned that the Properties window options are visual and easy to use. In addition to the many new properties coming from a Visual Basic 6 environment, using the Properties window is easier than ever. As usual, the description for each property is still visible on the lower portion of the Properties window, so you don't need to press the F1 key for help when you're not sure about a property's functionality.

TIP

Hopefully, you see the power of Windows Forms. The Opacity property used in conjunction with the TransparencyKey property has a great use if you're a consultant or a company providing demo software. You can literally make the form, or controls on the form, disappear before the viewer's eyes by using the properties correctly.

Let's say you have 20-day demo software and after the 30 days, the user must purchase the full version. Each day, starting with day 1, you could reduce the Opacity property by 5%. By the 20th day, the application would be literally invisible, so the user has to pay the money for the full version. If you're a consultant and you're worried about getting paid, just randomly change the Backcolor of controls to the same TransparencyKey color. When you do so, the controls become transparent, making it appear that data is disappearing. After the customer pays up, you can modify the code to be more user-friendly!

Now that you have your feet wet with the IDE, you can learn about how the applications you write using Windows Forms actually work.

NOTE

When working with controls on a form, you can select multiple controls with the Ctrl+click combination. After you've selected multiple controls, you can set properties on all the selected controls at the same time. You can also use Shift+click to select multiple controls, just like you would in Windows Explorer to select multiple files.

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