Introduction to Windows Forms Applications: Using Visual C# 2005 Express Edition

Lou Tylee

KIDware

February 2007

Overview

So you’ve installed Visual C# Express Edition on your computer and now you want to know what to do with it. Visual C# is one of the easiest programming languages to learn. Yet, even though it is easy to learn and to use, Visual C# can also be used to develop very powerful computer programs. The Visual C# Express Edition provides a sophisticated environment for building and testing Windows-based applications. This lesson will introduce you to the idea of Windows Forms applications using Visual C# Express Edition.

You’ve used Windows Forms applications before. Microsoft’s programs like Word, Excel, PowerPoint, Internet Explorer and the windows that appear within these applications (to open and save files, to print files) are all Windows Forms applications. These applications may not be written in Visual C#, but they do demonstrate the functionality you can put in your Visual C# Express applications. You can do just about anything using the C# programming language – you can write computer games, manage enterprise systems and databases, develop web applications, and build Windows Forms applications to help with tasks in your everyday home and work life.

You will learn about Windows Forms applications by opening and running a sample project in the Visual C# Express development environment. The sample project is called Hidden Note. It is a simple note editor that allows you to write and save text files in an encrypted fashion. These files can only be read when opened in the Hidden Note program, not by someone browsing through your file folders. So, before starting, you need to make sure you have this example project on your computer. To do this, please make sure you have downloaded the accompanying source code project files from the Beginner Developer Learning Center website and saved them in a folder on your computer.

Now, let’s get started. Follow these steps to get Visual C# Express running on your computer:

  • Click on the Start button on the Windows task bar.

  • Select All Programs, then Microsoft Visual C# 2005 Express Edition

(Some of the headings given here may differ slightly on your computer, but you should have no trouble finding the correct ones.) The Visual C# Express program should start. Several windows will appear on the screen, with the layout depending on settings within your product.

Opening the Sample Visual C# Express Project

What we want to do right now is open a project. Windows applications written using Visual C# Express are referred to as solutions. A solution is made up of one or more projects. Projects include all the information we need for our computer program. Most times, the words project, solution, program and application are used synonymously.

We will open the sample project using the Visual C# Express development environment main menu. Follow these steps:

  • Select File from the main menu, then click Open Project. An Open Project window will appear:

Bb330918.e07faa14-7f1d-4a84-823a-38def2dfe281(en-US,VS.80).png

  • Go to the Hidden Note folder containing the sample project.

In this project folder, among other things is a Visual Studio Solution file named Hidden Note.sln and a Visual C# Express Project file named Hidden Note.csproj. Open the Hidden Note solution file. Since there is only one project in this solution, you could also open the project file and get the same results, but it is better to always open the solution file.

Your Visual C# Express project may look something like this:

Bb330918.502ec207-392d-42f6-aa4e-496b7b628b64(en-US,VS.80).png

Look for the Solution Explorer window usually placed in the upper right side of the screen. If it is not there, choose View in the menu and select Solution Explorer. This lists the files in our solution. Right-click the file HiddenNote.cs file and choose Open. This is the main Windows Form in the Hidden Note project (we will look at the other Password.cs Windows Form later on).

When the HiddenNote.cs Windows Form is opened, Visual C# Express is in design view mode. This is the mode used to visually or graphically build Windows Forms applications. As opposed to the code view mode which shows the actual source code text of the application (we’ll cover the code view mode later on). In the Design window (the HiddenNote.cs [Design] tab) will appear a form that looks something like this:

Bb330918.ac451a68-247f-4e54-a889-9eff51067356(en-US,VS.80).png

This is one of two forms used in our project. It is the form where you or a user will write a note to be saved. We’re going to spend a bit of time explaining everything that is displayed here. This will introduce you to some of the vocabulary we use in Visual C# Express.

As mentioned, we call the displayed project window a Form. You have probably noticed that all Windows applications are built using forms of some type. At the top of the form is the Title Bar. It has an icon (little picture) related to the form (a notepad in this case), a title or description of what the form does (Hidden Note), and three smaller buttons that control form appearance. You may recognize the Minimize, Maximize, and Close buttons that are common on most windows applications, but we won’t worry about these buttons right now.

Bb330918.d5ab4022-d7b1-49d4-9b9e-d1fa1c9d97d6(en-US,VS.80).png

At the top of the form is a toolbar with four buttons with pictures on them. There is a large area under the toolbar where you can enter and edit text (a text box). Below the form are three other items named tbrNote (ToolStrip control that hosts the buttons at the top of the form), dlgOpen (OpenFileDialog control), and dlgSave (SaveFileDialog control). The toolbar buttons, text area on the form, and the things below the form are called Controls or Objects. Controls provide an interface, or line of communication, between you (or the user of your program) and the computer. You use the controls to tell the computer certain things. The computer then uses what it is told to determine some results and displays those results back to you through controls. By the way, the form itself is a control. If you’ve used any Windows applications, you’ve seen controls before - you probably just didn’t know they were called controls. As examples, check boxes for choices are controls, scroll bars to move through word processor documents are controls, menu items are controls, and the buttons you click on when opening and saving files are all controls.

If the toolbox window is not present on the screen, click View on the main menu, then Toolbox. Controls are grouped into categories according to what they do. To see a list of all the controls, make sure you have the All Windows Forms category group expanded. Scroll down the list to see all the controls. Many of these controls should look familiar to you. They are the same controls used in many Windows applications - such as a Button, a ComboBox, a PictureBox, etc. During design, controls are moved from the toolbox to the form by a simple drag and drop process. If you would like, you can add a new form to the project (from the main menu select Project | Add Windows Form | Click ‘Add’ button) and drag and drop various controls onto this new Form1 to experiment with their functionality.

Bb330918.7f414fd4-c5dd-486e-b5b2-1585bd40b136(en-US,VS.80).png

Controls for projects are selected from the toolbox

Every characteristic of a control (including the form itself) is specified by a property. Properties are used to give your project the desired appearance. Example control properties include names, any text on the control, width, height, colors, position on the form, and contents. Initial properties for controls are set using the Properties Window which is usually located on the bottom right:

Bb330918.626854f6-31a4-4ba5-b70e-74b06f5cb61d(en-US,VS.80).png

If the properties window is not present on the screen, click View on the main menu, then Properties Window. Click the Properties button (next to the Alphabetic view button) to see the properties. The drop-down box at the top of the window lists all controls on the current form. Under this box are the available properties for the currently selected object (frmNote in this case). Different views of the properties are selected using the toolbar near the top of the window. Two views are available: Alphabetic and Categorized. The properties are listed on the left side. The current value is listed on the right side. Clicking on the current value allows editing. Try changing some of the values for these properties – for example, try changing the BackColor property to a different color, or the Text property to something else.

As we mentioned before, this project will allow you to write and save encrypted messages. To open these messages, a user will have to enter a secret password. Now let’s take a look at the other Windows form in this sample project: Password.cs which is used to accept the password. Go back to the Solution Explorer window. Right-click the file Password.cs and choose Open.

In the Design window (the Password.cs [Design] tab), you will now see this:

Bb330918.87ffab69-1bff-4a9f-97d1-15dda1918a30(en-US,VS.80).png

Note the different title bar and icon (a padlock). There are also other controls on this form. There is a text area to type the password, a button to click once the password is entered and a check box to allow remembering the password. Go ahead and examine the different properties and values for each of these controls.

I think you get the idea that controls are a very important part of a Windows Form application, and you’re right. They are what allow your application to communicate with users – both to gather user input as well as to display output to users. Now, let’s run this example and get some insight into how this application and its controls works.

Running the Sample Visual C# Express Project

After opening a Visual C# Express Windows Form application, you want to start or run the program. This gets the program going and lets the user interact with the controls on the form and have the computer do its assigned tasks. We can run a project by using the toolbar under the Visual C# Express menu. Look for a button that looks like the Play button on a VCR, CD player, or cassette tape player. Click this button to run Hidden Note (the project we opened previously).

Bb330918.ee4eeb4c-500a-4859-9ee3-f64a919d7ffd(en-US,VS.80).png

Start Project Toolbar Button

You can also run a project by: (1) selecting the Debug menu heading, then clicking Start Debugging, or (2) pressing the <F5> function key.

The HiddenNote form will appear and look something like this:

Bb330918.489b8d67-1ff1-4d2e-b098-d7144516a197(en-US,VS.80).png

Notice the items we saw below the form are not visible, that’s because those controls (tbrNote, dlgOpen, dlgSave) do not provide a graphical user interface and thus do not need to be displayed on the Windows Form. Also, notice in the Visual C# Express title bar (in the main window) that the word Running appears in parentheses next to the project name:

Bb330918.0566e5da-fa93-4059-922d-f4b6ada9b1be(en-US,VS.80).png

It is important to always know if you are running or designing a program – this indication in the title bar will tell you.

The project is now running, but what is it doing? Nothing is happening, or is it? At this point, Visual C# Express is waiting for you, the user, to do something. We can say that your Hidden Note project is waiting for an event to occur. Nothing can happen in a Visual C# Express Windows Form application until an event occurs. We call C# an event-driven programming language. So, let’s cause an event.

An event occurs when you do something on the form - click on something with the mouse, type something in places where words can go, or maybe drag an object across the form. Hold your mouse over each of the toolbar buttons. A tooltip should appear telling you the function of each button. When the mouse moves over a button, we cause an event called a MouseOver event (the mouse has moved over the button). Click the button to open a note (the button with the folder). Doing this causes a Click event on the button. This Open File dialog box should appear:

Bb330918.80e2bcff-b0a2-487b-bdfb-4fc4379436c6(en-US,VS.80).png

Where did this come from? Remember the items under the HiddenNote form we saw when we displayed the form?

Bb330918.07ac2532-7f7b-4c3c-92a7-17cf4daed65a(en-US,VS.80).png

These items are also controls, but controls that appear only when the application is running. One of these controls (dlgOpen) is a dialog form control used to open files. When we caused the Click event on the Open Note button, the application displayed this dialog window. Notice this is the same dialog you see in every Microsoft Windows Form application (Word, Excel, Access, PowerPoint) when opening files. As such, it is called a common dialog control. Visual C# Express has an entire suite of such controls: dialogs to open files (seen here), save files (we will see soon), choose fonts, choose colors and control printing jobs. Use of these dialog controls in your Windows Form applications gives them a real professional appearance and they are familiar to your users. They also make your programming life a lot easier by providing powerful functionality to your applications. Common dialog controls are selected from the toolbox like all other controls. You can find a list of them under the Dialogs category:

Bb330918.d4948191-9b1a-440f-b229-c514b6a8c401(en-US,VS.80).png

The Hidden Note application can open any text file (.txt extension), like files created with the Windows Notepad (another Windows Form application by the way). The difference between Notepad and our Hidden Note Windows Form application is that Hidden Note can open files that have been ‘encrypted’. In the Hidden Note folder is an example encrypted file, named sample.txt. Select that file and click Open in the dialog control. The Password form we examined earlier should appear:

Bb330918.1002a8a4-cd0b-48b2-8c4c-45df4addc980(en-US,VS.80).png

Since this is an encrypted file, a password is needed to open it. The stored password is the word ‘hidden’. Type the password (note the asterisks masking the password), then click the button marked OK (causing a Click event). If you want the computer to remember the password (meaning, you only have to enter it once each time you run the application), put a check mark in the box next to Remember Password before clicking OK.

The password dialog should disappear and the contents of the decrypted file will appear:

Bb330918.a793d5a7-c0b7-434c-a7e0-2199e554801b(en-US,VS.80).png

How do you know the Hidden Note program did anything with the file it just opened? Open the file (sample.txt) in Windows Notepad to see it in its encrypted form:

Bb330918.df3f7383-97de-4cc3-9a23-b0843a383a49(en-US,VS.80).png

The first line (“Hidden Note File”) is used by the Hidden Note program to indicate it is an encrypted file. The remainder is the actual text file. I think you can see this would be hard for someone to decipher. So, the Hidden Note program does a nifty little trick.

We’ve seen how to open a file in the Hidden Note program. Other tool bar buttons allow erasing of the displayed text, saving the text in a file and stopping the program. Play around with the program and try out these other features. Operation is pretty straightforward.

At this point, we know that a project is made up of forms and controls that let the user provide and receive information to and from the computer. Properties describe the appearance of controls. By causing events with these controls, the computer application knows when to respond and generate the desired results. Next, we’ll look at the details of how a Windows Forms application is structured. To do this, we need to stop the project.

Stopping the Sample Visual C# Express Project

There are many ways to stop a Visual C# Express project. We will use the toolbar in Visual C# Express. Look for a button that looks like the Stop button on a VCR, CD player, or cassette tape player (you may have to move the project form down a bit on the screen to see the toolbar). Click on this button (you may have to click it twice). The project will stop and Visual C# Express will return to design mode.

Bb330918.d54b0914-9f9b-4433-b403-5a47004b131b(en-US,VS.80).png

Stop Project Toolbar Button

Alternate ways to stop a project are: (1) Selecting the Debug menu heading, then clicking Stop Debugging, or (2) Click the Close button found on the Windows form application itself. It is the little button that looks like an X in the upper right corner of the form.

Event Methods

In the Hidden Note program, we see that by interacting with the controls (typing text, clicking toolbar buttons, typing passwords, choosing different options), we make things happen by generating control events. We say that C# is an event-driven language and is governed by an event processor. Once an event is detected, the project finds a series of instructions related to that event, called an event method. That method is executed, then program control is returned to the event processor:

Bb330918.8db3f528-f9c8-4824-8dea-1315b2a2d8be(en-US,VS.80).png

Event methods associated with various controls are where we do actual computer programming. These methods are where we write Visual C# language statements. In this lesson, we won’t do any coding of the C# language ourselves, get a feel for the language syntax, and see it’s pretty easy to get a feeling for what happens in these methods.

Event methods are viewed in the Code Window. There are many ways to display the code window. First, select the desired form in the Solution Explorer window. Then, use the View Code button found in the Solution Explorer window, alternately you can right-click on the file and select View Code:

Bb330918.3509ee0f-5eaf-4925-98b4-e7c8e400a5be(en-US,VS.80).png
Bb330918.ca1d1e73-8730-4b98-9aad-6fe0278bab1f(en-US,VS.80).png

Or, click View on the main menu, then Code. Or, as an alternate, press the F7 function key. Each form in a project has its own code window. Find the code window for the HiddenNote form. It will appear in the main window under the HiddenNote.cs tab:

Bb330918.c8cb003c-8870-4ad5-a1d3-14529d3ad896(en-US,VS.80).png

At the top of the code window are two drop-down boxes. The one on the right side is the method list. It lists all the methods (including event methods) used in the code. Click on the drop-down arrow in the method list. Select tbrOpen_Click as the method. tbrOpen is the ToolStripButton control that will open a file if it’s clicked. You should see this:

Bb330918.28ea2091-0729-4cc8-bf45-a0c952d9f8fc(en-US,VS.80).png

Displayed is most of the Click event method for the control name tbrOpen (the method is named tbrOpen_Click). This is the code executed when a user clicks the toolbar button to open a note. And even though you may not know any Visual C# right now, you should be able to figure out what is going on here. The first thing you should know is that any line beginning with two slashes (//) in green is a comment that gives some information as to what the following line of code is doing. The steps for this event method are:

  1. Display the open file dialog box.

  2. If the user clicks OK, get a filename for the input file. If OK is not clicked, exit the method.

  3. Read the first line of the file.

  4. If the first line says ‘Hidden Note File’ (recall we put this at the top of encrypted files), then it is an encrypted file. If not, then just open as a normal text file.

  5. If it’s an encrypted file, display the Password form and make sure the correct password is entered or the user has checked the Remember Password check box (chkRemember) on the Password form (frmPassword).

  6. If the correct password has been entered, decrypt the file (using the ShiftText method) and place the results in the text box property of the text box control (txtNote.Text) on the form.

  7. When done, close the input file.

Take a look at the tbrSave_Click event method (the code executed when the user wants to save a note):

Bb330918.f01df92f-f667-4012-92b4-af5ef06ed168(en-US,VS.80).png

The steps followed here are:

  1. Display the save file dialog box.

  2. If the user clicks OK, get a filename for the output file. If OK is not clicked, exit the method.

  3. After the user clicks OK in the dialog box, write the first line of the file so we know it is encrypted.

  4. Encrypt the contents of the text box control (txtNote.Text) using the ShiftText method and place the results in the output file.

  5. When done, close the output file.

Take a look at the other event methods for the HiddenNote form (tbrErase_Click, tbrStop_Click, frmNote_Closing). Each one of these methods is pretty easy to understand, even without a lot of programming knowledge. There is one other method in the code window that is not an event method. This method is the ShiftText method used to encrypt/decrypt the contents of the text box control. To see this method, select ShiftText in the method list:

Bb330918.78aa2de7-01db-490c-ad03-597c03a8262c(en-US,VS.80).png

So, how does this work? The text to be encrypted or decrypted (the text from the text box control) is contained in the variable named textIn. For the encryption, it looks at each letter in that variable and shifts it one position to the left (the direction variable is -1). In other words, an ‘e’ becomes a ‘d’, an ‘R’ becomes a ‘Q’ and so on. It’s a simple encryption scheme, but effective – recall the sample.txt file looks very confusing. With such an encryption, the word ‘Microsoft’ becomes ‘Lhbqnrnes’. To decrypt a text variable, the letters are simply shifted one position to the right (the direction variable is +1). The code to do this encryption and decryption uses some C# language structures that you may not be familiar with, but the logic is straightforward.

The Password form has event methods you can also examine. To view its code window, select the Password form in the Solution Explorer window, then open the code window using one of the previously described methods. The code is displayed on the Password.cs tab:

Bb330918.bdba284a-3c6f-45e2-9a7e-5d4d534e2975(en-US,VS.80).png

The frmPassword_Load event method is executed when the form is first opened (it clears the password text box):

Bb330918.22a4f95d-6b4a-4a42-8ae5-7b9a296d9cf6(en-US,VS.80).png

The btnOK_Click method is executed when the user clicks the OK button. This method checks to see if the password is correct (the correct password is stored at the top of the code window in the constant variable myPassword and its value is the text “hidden”).

Bb330918.1ce86b3a-b697-40e8-97bc-cfa63520e203(en-US,VS.80).png

The txtPassword_KeyPress event is executed whenever a key is pressed in the password text box (txtPassword):

Bb330918.9ec5680d-b918-44cb-bfaa-ee9bb08aa324(en-US,VS.80).png

In this code, we check to see if the user pressed the <Enter> key (represented by a character code of 13). If so, we simulate a click on the OK button. Again, you should see that the code written here is fairly easy to understand.

What Now?

In this lesson on Windows Forms applications, we looked at an example project (Hidden Note) and learned the important parts of such a project and how these parts work together. We learned that projects are built on forms. Forms use controls to gather information from a user and to provide feedback to a user. The properties of these controls govern their appearance on the form. We learned that C# is an event-driven language. This means when a user interacts with a control, an event is generated. Once an event occurs, the code (written using the Visual C# language) residing in the corresponding event method is executed. So, now what should you do with all this new information?

Customizing the Windows Form application

After learning more Visual C# and more about the development environment (including controls, properties, events), you might like to add more features to the Hidden Note application. Here are some of my ideas – I’m sure you have your own:

  • Use graphics and colors to make the interface a little ‘prettier’

  • Add simple formatting features to the text box – change font name, font size, font type

  • Add ‘selective’ formatting by replacing the text box control with a rich text box control

  • Add simple menus to the application

  • Add printing capabilities to the application

  • Research and implement other encryption possibilities.

  • Change the secret password from “hidden” to something else

Learning More

Hopefully, this lesson has whetted your appetite to learn more about Visual C# Express Windows Forms applications. You may already have some ideas about applications you would like to build. There is a wealth of material out there to help you gain the knowledge you need to start building your own projects. The bookstores have many books to help you along. The Internet is full of self-help tutorials. There is no lack of learning material. Our company, KIDware, offers two particular tutorials that you may find useful.

Our first tutorial is entitled Beginning Visual C# Express. This tutorial is written for the absolute beginner - no programming experience is required, but familiarity with Windows use is expected. The tutorial is presented using a combination of over 400 pages of course notes and actual Visual C# Express examples. Ten "plain-English" lessons explain the Visual C# Express toolbox, event methods, and many elements of the C# computer language. Examples are used to demonstrate every step in the application building process. The tutorial also includes several computer projects that illustrate practical applications of Visual C# Express, including loan calculators, graphics programs, portfolio managers, checkbook balancers, and even a simple video game! Further details can be found at:

https://www.kidwaresoftware.com/beginvcse.htm

If you’re fairly competent with Visual C# Express, our second tutorial, Home Projects With Visual C# Express, is for you. This tutorial explains (in simple, easy-to-follow terms) how to build a Visual C# Express Windows Forms project. You learn about project design, the Visual C# Express toolbox, many elements of the Visual C# language, and how to debug and distribute finished projects. The projects built include:

  • Dual-Mode Stopwatch - Allows you to time tasks you may be doing.

  • Consumer Loan Assistant - Helps you see just how much those credit cards are costing you.

  • Flash Card Math Quiz - Lets you practice C# addition, subtraction, multiplication and division skills.

  • Multiple Choice Exam - Quizzes a user on matching pairs of items, like countries/capitals, words/meanings, books/authors.

  • Blackjack Card Game - Play the classic casino card game against the computer.

  • Biorhythm Tracker - Discover your physical, emotional and intellectual cycles for any day you choose.

  • Weight Monitor - Track your weight each day and monitor your progress toward established goals.

  • Home Inventory Manager - Helps you keep track of all your belongings - even includes photographs.

  • Snowball Toss Game - Lets you throw snowballs at another player or against the computer - has varying difficulties.

The product includes over 700 pages of self-study notes, all Visual C# Express source code and all needed graphics and sound files. Further details can be found at:

https://www.kidwaresoftware.com/buildvcse.htm

Thanks for reading through this brief lesson. We hope it’s given you an idea of the power behind Visual C# Express and how it can be used to build commercial quality, full-featured Windows Forms applications.