You are on page 1of 51

Visual Programming

Graphical User Interfaces (GUI) allow a user to interact easily with the program using different visual
components. On the early days of the computer world, applications are text based and you type commands
and input to make the program useful. You need to memorize a long list of commands to be able to work
properly with the program. Modern software applications have graphical user interfaces. You see them in
almost every program you use now. A professional looking graphical user interface is easy in the eyes and
has a simple, yet attractive look and feel. A good graphical user interface also makes the commands more
accessible and organized by using menus and grouping components.
But creating a program with a user interface was once a tedious task. For you to even create a simple
window that displays a message, you need to type lots of codes. Creating an application with a graphical
user interface was hard until the arrival of Visual Programming. Visual Programming makes it easy for
you to create GUI applications by providing you a "canvas" where you simply drag the controls from the
toolbox. Controls are visual elements that compose the GUI. You can interact with these controls to
perform their functionality. Examples of controls are buttons, text boxes, labels, checkboxes, and radio
buttons. The term "visual" in Visual C# was from the concept of visual programming.
Microsoft uses the term Windows Forms to represent every window in an application. Visual Studio allows
you to create Windows Forms Applications easily. You can then create and design the form in the Design
View.

Figure 1 - Visual C# Express Design View

Figure 1 shows the Design View in Visual C# Express 2010. You can see the form and some controls
"drawn" in its surface. With the Designer View, you can see how the form will look when you run the
program. The code for drawing and initializing controls are hidden from the programmer so you can
concentrate on the functionality of the application.
You can use Visual Studio's tools for designing controls such as aligning, anchoring, docking, and resizing
controls. Visual programming saves development time and suitable for Rapid Application Development.
Other languages that do not support visual programming requires dozens of code before you can even
create a simple window that shows a short message.

Creating a
Application

Simple

Windows

Forms

You will now experience visual programming which is the "Visual" in Visual C#. Please note that this lesson
guides you to the creation of a simple windows application which uses basic event-handling. I will show
the steps for doing these and briefly discuss them. The concepts of forms, controls, event-handling, and
certain parts Visual Studio used for designing will be discussed in their respective lessons.
Open Visual C# Express and go to File > New Project. Then from the list of templates, choose Windows
Forms Application. A Windows Forms Application is a type of application that has a graphical user interface.
Name the project MyFirstWindowsApplication.

Figure 1 - New Project Window

You will be presented with a blank form. The selected tab tells that you are viewing the Form1.cs file in
Designer View.

Figure 2 - Newly Created Blank Form

Two code files will be created that represent the form. But for now, we will concentrate on the file that is
used to add functionality to the form. The form can be viewed in two modes, the Design View and Code
View. The Designer will be shown if you are in design view. You will see here the actual form and any visual
and non-visual controls you will add soon.
You can also resize the forms by dragging the resizing handles of the form while in the Design View.

Figure 3 - The Resizing Handles of the Form

Adding Controls to the Form


All the controls are located in the Toolbox. The Toolbox can be accessed via the Toolbox tab located by
default at the left of the IDE. If it is not shown, you can go to View > Other Windows > Toolbox.
Hover your mouse over or click the Toolbox tab to show the actual Toolbox.

Figure 4 - Toolbox Tab

The Toolbox is divided into categories and the most commonly used controls are located in the Common
Controls category. To open a category and expose its control, simply click the category. The Toolbox will
auto-hide by default. If you don't want that behavior, then you can click the pin icon beside the close button
of the Toolbox.
To add controls to the form, choose a control in the Toolbox and double click it. Alternatively, you can drag
the control from the Toolbox to the form. Please note that you can only add controls to the client area of
the form. The client area is the blank area of the form. You can delete a control or controls by selecting it
in the designer and hitting Delete in your keyboard. Add a button control to the form. Most controls also
has resizing handles just like the form itself. Resize and position the button as shown if Figure 5.

Figure 5

Changing the Properties of Controls


You can change certain properties of the form and controls. We use the Properties Window to view and
change the value of all the available properties of a selected control in the Design View. Note that some
properties are not shown in the Properties Window and can only be accessed in code.
Selecting a control is equivalent to single clicking a control in the Designer. For a demonstration of modifying
control properties, select the button in the form, then go to the Properties Window. You can pin the
Properties Window if you will be working with it frequently.

Figure 6 - Changing Properties

Find the Text property and change its value to "Click Me".

Figure 7 - Changing the Value of a Property

The text inside the button in the Designer will update.

Figure 8 - Updated Windows Form

You can also click the form in the Designer and change the Text property. When selecting the form, you
need to click on any area of the form but not on the controls it contain.

Adding Event Handlers to Controls


The final part of this tutorial is showing you how to add event handlers to certain events of the controls.
Events trigger when certain happenings occur. We put event handlers to an event. Event handling will be
discussed in detail in a separate tutorial. Each control has its own default event. For example, the Button
control has Click as its default event while the Form control has a default event of Load. Event handlers
are methods that is associated with an event, and they execute when the associated event happens.
The easiest way to add an event handler is to double click a control in the Designer. You can only do this
if you want to add event handlers to the default event of a control. To demonstrate this, double click the
button in the Designer. Visual Studio will automatically create an event handler and attached that event
handler to the default event of the double clicked control. Once the event handler is created, you will be
taken to the Code Editor, with the cursor positioned inside the generated event handler. All you need to do
is type the codes that will run when the event occurs.

Figure 9 - Newly Created Event Handler

Don't mind the other parts of the code as there will be a seperate lessons that discuss them. Type the
following code inside the event handler. Please only type the code inside the event handler of the following
code. I included the event handler so you can clearly see where to type the code.
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show("You clicked the button!");
}

The MessageBox class allows you to call a message box used to prompt user with messages and
information. The Show method shows the message box with a specified message. You will learn more
about the MessageBox class later. Run the program and click the button. You will be presented with a
message window with the message you specified as an argument to the Show method.

Another way of adding event handlers to events of controls especially for non-default events, is by going
to the Properties Window. To demonstrate this, let's add a Load event to the form. Go back to Design View
by clicking the Design Tab, or using the Shift + F7 shortcut.

Select the form in the designer then go to the Properties Window and find the Events button. It is
represented by a thunderbolt icon. If it is not visible, be sure that a control is selected in the Designer.

The Properties Window will now show a list of events for the selected control in the Designer. Find
the Load event of the form. Clicking the combo box beside it will show you the list of valid methods for the
event that exist in the code of the form. You can then choose which method to attach to this event. We
can also create a new event handler by double clicking the selected event in the Properties Window. You
will be taken to the Code Editor with the proper event handler created for you. Add the highlighted code.
private void Form1_Load(object sender, EventArgs e)
{
button1.Text = "Text changed by the Load event";
}

This statement will modify the Text property of button in the form. The Load event of the form occurs once
the form is finished loading. So when you run the program once more, as soon as the program has finished
loading, the text inside the button will be changed.

You have now successfully created an simple event-driven windows forms application using the tools
available in Visual Studio and Visual C# Express.

Event Handling
Graphical user interfaces in .NET and Visual C# uses event handling mechanism to handle events that
occur while the program is running. Events are behaviors or happenings that occur when the program is
running. Event handling is the process of monitoring for certain events to occur, and then executing
codes when a specific event happens. Windows forms use event handling to add functionality and respond
with the user. Without event-handling, forms and user interfaces are pretty much useless. This tutorial
assumes that you already learned the concepts of delegates and events.
Events are declared using a delegate as a type. Delegates hold references to methods. The following is an
example of declaring a delegate and an event.
public delegate void SampleEventHandler(int);

public event SampleDelegate SampleEvent;


Based on the declaration of the delegate, the methods that it can accept must not return a value( void)
and accepts a single

intargument. We then used this delegate type to create our event.

We will now add event handling to the event. Event handlers are methods that match the delegate type
of the event and the ones that will be executed when the event occurs. Event handlers are attached to an
event. Attached event handlers are executed when the event occurs. You can attach multiple event handlers
to the event and they will all run when the event occurs. To attach an event handler to an event, you first
create it. When creating an event handler, be sure that it matches the signature of the delegate that the
event uses. For example, considering the delegate created above which has a return type of
an

void and

int parameter, our event handlers should also have a void return type, and an int parameter

(please note that access specifier is not important).


public void ShowMessage(int number)
{
MessageBox.Show("Hello World");
}
We can then attach the event using the

+= operator like this:

SampleEvent += new SampleEventHandler(ShowMessage);

To activate the event, we call it passing the required arguments the same way we call methods.
SampleEvent(3);

Event Handling in Windows Forms


To demonstrate using events on windows forms, create a new Windows Forms Application and name it
EventHandling. Double click the form and Visual Studio will automatically create an event handler and
attach it to the Load event of the form. The
events of controls have a delegate type of
the

Load event has a delegate type of EventHandler. Most

System.EventHandler. The following is the definition of

EventHandler delegate.

public delegate void EventHandler(object sender, EventArgs e)

As you can see with the definition of the delegate, it has no return type and has two parameters,
an

object, and an EventArgs instance. The object sender represents the control that activates the

event. We will demonstrate its use later. The second argument is an instance of the

EventArgs class.

This can be called as the event argument and they contain data about the event that happened.
The

EventArgs is actually a base class and contains no useful members. Certain events will have event

arguments that are derived from

EventArgs and contain useful properties that the event handler can

use. You will notice that the created event handler by Visual Studio matches the signature of
the

EventHandler.

private void Form1_Load(object sender, EventArgs e)


{

If you want to create event handlers manually, then be sure to follow the signature of the delegate type
of the event. Visual Studio proposes a naming convention for event handlers, as seen in the generated
event handler. When naming event handlers, type the name of the control(specified by its

Name property)

followed by an underscore and then the name of the event. You can ignore this convention if the event
handler will be used by multiple events as we will see later.

Communicating with the Source Control


You have seen that the

EventHandler delegate has two parameters, and the first of them is an object

which represents the control that sent the event. Since it is of type
of the event because every control is derived from the

object, any control can be a source

object base class. Since the sender is converted

to an object, we need to convert it back to the proper control to access its useful properties. To demonstrate
its use, add a button to the form. Change the

Text property of the button to "Hello World!".

Double click the button to generate an event handler for its


the

Click event. Like the Load event,

Click event also has a type ofEventHandler. Use the following code for the event handler.

private void button1_Click(object sender, EventArgs e)


{
Button source = (Button)sender;
MessageBox.Show("The message inside the button is " + source.Text);
}

Run the program and click the button. A message box will be shown telling the text inside the button that
sent the Click event.

The first line of the event handler converts the sender object to a
its

Button using casting so we can access

Text property. We then call the Show method of the MessageBox class to show the value of the

Text property of the button that sent the event.

Event Arguments
The second parameter which actually varies depending on the event is an event argument. The most
common is the

EventArgs which is the base class of event arguments. It has no properties you can use

in your event handler. To demonstrate an event that has a different event argument, we will use the
MouseClick event of the button which is a better version of the Click event. Since it is not the default event,
we can access it in the events section of the Properties Window. Be sure that the button is selected in the
designer. Click the thunderbolt icon to show the events of the button. We need to remove the
handler first so it will not conflict with theMouseClick event. Find the
next to it. Then find and double-click the
delegate
ordinary
is

type

of

Click event

Click event and delete the value

MouseClick event. TheMouseClick event has a different

MouseEventHandler.

It

has

the

same

signature

as

the

EventHandlerdelegate, but it has a different type for its event argument which

MouseEventArgs. The MouseEventArgs is derived from EventArgs. It contains useful

properties such as which button(left or right) of the mouse is clicked, the number of clicked done, how
much the mouse wheel was rotated, and the point location of the click relative to the source control. Use
the code below for the

MouseClick event handler.

private void button1_MouseClick(object sender, MouseEventArgs e)


{
MessageBox.Show("You clicked at point (" + e.X + ", " + e.Y + ")");
}

The code above uses the event argument parameter to access the x and y coordinates of the point where
the mouse was clicked. The output below my vary depending on where you click on the button.

There are many more event argument types and each offers useful properties about the event that took
place.

Using the Properties Window to Attach Event Handlers


We already know that aside from double-clicking controls, we can use the Properties Window to attach
event handlers to events. We click the thunderbolt icon to go to the Events section of the Properties
Window.

The top combo box is used to select controls in the Designer. This is useful when you can't select certain
controls because they aren't visible or very small.
Find the desired event. To attach an event handler to an event, you can double-click the name of the event
to generate an event handler for the specified event. Alternatively, if you already have created event
handlers, you can click the dropdown button to view all the valid event handlers that match the signature
of the delegate type of the specified event.

Using Identical Event Handlers for Multiple Events


Please note that you can use a single event handler for multiple events that have the same delegate type.
To do this, you need to first create the event handler with the proper signature. Then go to the Events
section of the Properties Window and find the events you want. Instead of double clicking, choose the
event handler you created. Now find another event and choose the same event handler.

Separating Design and Functionality


When we create a new windows form, a class that inherits from System.Windows.Forms.Form is
generated. This class is separated in two files thanks to the feature called partial classes. Partial classes
allow you to separate definitions of a class in different files within the same project and namespace. With
the introduction of partial classes in .NET 3.5, Visual Studio was able to separate design from functionality.
This allows a programmer to concentrate on the functionality of the application. The name of the files will
have the following pattern:
FormName.cs
FormName.Designer.cs

where FormName is the name of the form, for example, Form1. A third file with .resx extension is used
for resources of the form and will be discussed in a separate lesson. When we create the form, add controls,
and modify properties, all the code is written in a somewhat hidden file with a .Designer.cs extension. If
you can't see it, find the .cs file for the form in the Solution Explorer and click the arrow button beside it.

Double-clicking that file will allow you to see all the codes that were generated by Visual Studio. The code
contains methods for disposing and initializing the controls. You can see the controls being declared and
properties, such as Location and Text, are set depending on what you specified in the Properties Window.
You will also see event handlers being attached to events of controls. If you can't see the code, it is hidden
by default and is labeled "Windows Forms Designer generated code". Just click the plus icon to its left to
show it. You will see that the code for initializing the controls and their properties and events is located
inside a method called InitializeComponent. This method is called in the form's constructor located at
the main code file for the form's class. The codes in the Designer file is initially hidden because Visual
Studio want's you to use the Designer and the Properties Window instead of writing all these codes
manually.

The MessageBox Class


he System.Windows.Forms.MessageBox is a static class that is used to show message boxes for
prompting, confirmation and warning users. To show a message box, simply call the Show method of
the MessageBox class. The simplest version of the Show method is the one that accepts a string message
as an argument.
MessageBox.Show("Hello World!");

You can also specify the title of the message box by using another overloaded version of the Show method.
MessageBox.Show("Hello World!", "A Message");

You can also change the buttons that will be shown in the message box if you don't want to use the default
OK button. You can do this by using the System.Windows.Forms.MessageBoxButtons enumeration.
MessageBox.Show("Hello World!", "A Message", MessageBoxButtons.OKCancel);

The table below shows the members of the MessageBoxButtons enumeration.


Member

Buttons Shown

AbortRetryIgnore

Abort, Retry, Ignore

OK

OK

Member

Buttons Shown

OKCancel

OK, Cancel

RetryCancel

Retry, Cancel

YesNo

Yes, No

YesNoCancel

Yes, No, Cancel

The Show() method returns a value from the System.Windows.Forms.DialogResult enumeration. This
is useful to determine what button you pressed in the message box. For example, if you click the "Yes"
button in the message box, then the Show() method will return the value DialogResult.Yes.
DialogResult result;
result = MessageBox.Show("What is your choice?");

if (result == DialogResult.Yes)
{
//You pressed the Yes button
}
if (result == DialogResult.No)
{
//You pressed the No button
}

Please

note

that

the Form class

also

has

a DialogResult property.

This

is

not

the System.Windows.Forms.DialogResult.
You can also add an icon for your message box to further imply the purpose of the message. You do this
by using the members of theMessageBoxIcon enumeration.
MessageBox.Show("Hello World!", "A Message",
MessageBoxButtons.OK, MessageBoxIcon.Information);

The table below shows the different icons that you can use for your message box.
Icon

Member

Usage

Asterisk
Information

Used when showing information to the user.

Error
Hand
Stop

Used when showing error messages.

Exclamation
Warning

Used when showing warning messages.

Question

Used when asking a question to the user.

You can use the MessageBoxIcon.None to indicate that the message box will have no icon.
The MessageBoxDefaultButton enumeration tells which of the button is the default, that is, the one that
is pressed when the enter key in the keyboard is pushed. It has only 4 members which
are Button1, Button2, Button3, Button4. For example, in a message box that has an OK and a Cancel
buttons, using MessageBoxDefaultButton.Button1 will make the OK button as the default. When the
message box is shown and you pressed Enter in the keyboard, the OK button is pressed.
MessageBox.Show("Hello World!", "A Message",
MessageBoxButtons.OKCancel, MessageBoxDefaultButton.Button1);

Properties

Description

Anchor

Specifies how the control relocates and resizes whenever the form
is resized.

AutoSize

If set to true, the control will automatically size itself to fit the
contents.

BackColor

The background color of the control.

BackgroundImage

Allows you to add a background image to the control.

BackgroundImageLayout

Specifies the way the background image is placed and resized.

Bottom

Gets the distance in pixel between the top of the control's container
and the bottom of the control.

CausesValidation

Specifies whether the control will raise validation events.

ContextMenuStrip

Allows you to add a context menu to the control.

Controls

A collection of child controls within this control.

Dock

Docks the control to one of the edges of the window.

Enabled

Tells whether the user can interact with the control. Set to false to
disable the control.

ForeColor

The foreground color of the control. This is also the font color of
the text inside the control.

Height

The height of the control in pixels.

Left

Gets or sets the distance between the left edge of the control and
the left edge of its container.

Location

The location of the control relative to its container.

Locked

Specifies whether the control can be moved or resized in the


designer.

MaximumSize

Specifies the maximum size of the control.

Margin

Specifies the margin between this control and another control.

MinimumSize

Specifies the minimum size of the control.

Name

The name of the control. This is used to reference the control in


code.

Padding

Specifies the interior spacing of the control.

Parent

The parent of the control.

Right

The distance between the right edge of the control and the left
edge of its container.

Size

The size of the control. Composed of Width and Height subproperties.

TabIndex

Specifies the number of the control in the tab order of its container.

TabStop

Specifies whether the control can be accessed by the tab key.

Tag

Used to assign special or useful values about the control.

Text

The text to be shown inside of the control.

TextAlign

Specifies the alignment of the text of the control.

Top

The distance between the top edge of the control and the top edge
of its container.

Visible

Sets the visibility of the control.

Width

The width of the control in pixels.

Controls
Controls are visual components that compose the graphical user interface. Everything you see in a GUI is
a control, including the form itself. Controls are located at the Toolbar grouped inside different categories.
Most of the controls inherit from theSystem.Windows.Forms.Control base class which exposes several
properties, methods, and events common to those controls.

Control Properties
The following are some of the useful properties of the Control class.
Figure - Control Properties

The most important property in the table is the Name property. This property allows you to reference the
control in code. The following discusses more properties common to most of the controls.

Changing the Background Color of the Control


We use the BackColor property of the control to change the color of the background. Find
the BackColor property in the Properties Window and click the drop down button. You will be presented
with a window with three tabs. Each tab presents a different set of color.

The System colors the colors your operating system uses as default colors for controls. The Web tab shows
colors that are safe to use for the web. And the Custom tab shows much more colors. Alternatively, you
can type the RGB values of the color separated by commas in the text box next to the property.

Adding a Background Image


We can change the background image of a control by using the BackgroundImage property. As an
example, let's change the background image of a form. Go to Properties Window while the form is selected
and find the BackgroundImage property.

You will be presented with a window which allows you to choose a resource. For now, choose local resource
and browse for an image by clicking the Import button.

Once you choose an image, click OK. The background image will now show up on the form. The alignment
and size of an image may not be what you desired. There is another property called
the BackgroundImageLayout property.

It

accepts

values

from

theSystem.Windows.Forms.ImageLayout enumeration.
Value

Description

None

The image will be positioned using its top left corner with no resizing of the image.

Tile

If the image is smaller than the client area of the control, the image will be repeated until it
fills the form.

Center

The image is centered within the control's client area.

Stretch

The image will be resized to fit the client area of the control.

Zoom

The image will be fitted to the client area of the control without losing its aspect ratio.

Most of the time, Stretch will work fine. The form below has a background image with an image layout
of Stretch.

The Text Property


The Text property defines the text or caption inside the control. The text that the Text property represents
varies on different controls. For example, Text property of the form gets or sets the caption located in its
caption bar. The Text property of the button represents the Text inside the button. The Text property of
a textbox represents the text inside the text box. We can use the TextAlign property to align the text in
different locations of the control. If you click the TextAlign properties' drop down box in the Properties
Window, you will be presented with a small window that allows you to easily point which location you want
the text to be aligned.

Changing the Font of the Control


We

can

change

the

font

type,

color,

size,

and

style

of

the Font and ForeColor properties. Let's use a button control as an example.

the

control

by

using

To change different font properties of the control, find the Font property in the Properties Window. You
will notice a drop down button in its left. Open it up and more properties about the font will be exposed.

The useful once are the Name, which defines the type of font to use, the Size which indicates the size of
font, Unit which

tells

the

unit

to

use

for

the

size

of

the

font,

and Italic, Strikeout, Underline and Bold to add styles to the control. Alternatively, you can use the
button to the right of the font property to open the Font Window.

Here, you can choose the font type, the font style, the size and add certain effects. You can even see a
preview of the font. With these, you can customize the font of the controls.

Enabling and Disabling Controls


We can use the Enabled property to tell whether a control can receive focus and user interaction. We set
the property to false to disable the control and true to enable it. When we disable the control, its appearance

Event

Description

BackColorChanged

Occurs when the background color was changed.

BackgroundImageChanged

Occurs when the background image was added or changed.

Click

Occurs when you click the control with the left mouse button.

ControlAdded

Occurs when a child control is added to this control.

ControlRemoved

Occurs when a child control was removed from this control.

DoubleClick

Occurs when you double click the control.

DragDrop

Occurs when the drag drop operation is completed.

EnabledChanged

Occurs when the control is enabled or disabled.

Enter

Occurs when the control is entered.

FontChanged

Occurs when the font properties are changed.

ForeColorChanged

Occurs when the fore color of the control is changed.

GotFocus

Occurs when the control got the focus.

KeyDown

Occurs when a key in the keyboard is pressed while the control has
the focus.

KeyPress

Occurs when the key in the keyboard is pressed and released while
the control has the focus.

KeyUp

Occurs when a pressed key in the keyboard is released while the


control has the focus.

Leave

Occurs when the input focus leaves the control.

LostFocus

Occurs when the focus of the control is lost.

MouseClick

A more advanced version of the Click event.

MouseDoubleClick

A more advanced version of the DoubleClick event.

MouseDown

Occurs when a button in the mouse is down while inside the control.

MouseEnter

Occurs when the mouse pointer enters the control.

MouseHover

Occurs when the mouse pointer rests on the control

MouseLeave

Occurs when the mouse pointer leaves the control.

MouseMove

Occurs when the mouse pointer moves while inside the bounds of the
control.

MouseUp

Occurs when a pressed button of the mouse is released while inside


the control.

MouseWheel

Occurs when you move the mouse wheel while the control has the
focus.

Move

Occurs when the control is moved.

Paint

Occurs when the control is redrawn.

ParentChanged

Occurs when the parent control of this control changes.

Resize

Occurs when the control is resized.

TextChanged

Occurs when the Text property of the control is modified.

Validated

Occurs when the control is finished validating.

Validating

Occurs when the control is validating.

VisibleChanged

Occurs when the Visible property is changed.

may change. For example, when we disable a button (setting its Enabled property to false), its color and
appearance will change. Note that the change is only visible when you run the form and not in the designer.

When a control is disabled, it will not receive focus or events. For example, if a button is disabled, you
cannot click it.

Making Controls Invisible


You can temporarily hide a control by setting the Visible property to false. The Visible property is a
boolean property which tells whether the control is visible or not. Setting to false makes the control hidden,
and setting it to true makes the control visible. Note that you will only see the effect when you run the

form and not in the designer. This allows you to still select the control in the designer even if the Visible
property is set to false.
More about the properties and features of controls will be discussed in the following lessons.

Control Events
The following table shows the some useful events common to most controls.
We will discuss most of the events above in later chapters.

Control Methods
The following are the most useful methods of the Control class.
Methods

Description

BringToFront

Brings the control to the front of the z-order.

Contains

Tells whether a child control is contained inside this control.

CreateControl

Creates a new control and add it to this control.

FindForm

Retrieves the form that the control is on.

Focus

Sets the focus to this control.

GetContainerControl

Gets the control that serves as the container of this control.

Hide

Hides the control.

Refresh

Forces the control to invalidate its client area and immediately redraw itself and any child cont

Select

Activates the control

SendToBack

Brint the control to the back of the z-order.

Show

Shows a hidden control.

Update

Causes the control to redraw the invalidated regions within its client area.

The Control class also offers some methods that allow you to manually trigger events of the control. Such
methods starts with Onfollowed by the name of the event. For example, the OnClick event triggers the
Click event when called. Note that some events cannot be triggered by user interaction such as
the Paint event. If you want to trigger such events, use the methods offered by the Control class. You
will learn more about these methods when we delve deeper into the world of C#.

Note that these properties, events, and methods are inherited by most of the controls thanks to inheritance.
Therefore, I may not include them again when I present the properties, events, and methods of individual
controls unless they are very significant to the control.

Naming Your Controls


Always make a habit of naming controls. We name our control using its Name property. Naming controls
follows the guideline for naming variables such as spaces, special characters, and the use of keywords are
prohibited. There have been many naming conventions that emerged when it comes to naming controls.
You can name the control depending on its use. For example, a text box use to retrieve the first name of
the user can simply be namedfirstName just like a normal variable. But when naming controls, it is better
to prefix the actual names with the name of the control. For example, instead of simply firstName, we
can use textBoxFirstName. With that convention, we will know, using IntelliSense, that we are working
with a text box or any control.
Another technique used by others is abbreviating the control names. For example, instead of using
textBoxFirstName, you can usetxtFirstName. The txt is short for the textbox. There has been a list of
abbreviations for every control and you can even use your own abbreviation as long as it is clear to you
and to others who will look at your code.
Another naming convention is the reverse of the first one where you place the descriptive name first
followed by the type of control and also uses camel casing. For example, a text box for retrieving the first
name of the person can be named firstNameTextBox or a button used for calculating can be
named calculateButton.

Scenario

Name

A Button used to confirm a message.

buttonConfirm, confirmButton, btnConfirm

A TextBox used to accept email address from textBoxAddress, addressTextBox, txtAddress


user.
A Form used
information.

for

obtaining

personal formPersonalInformation,
personalInformationForm,

A ComboBox to show a list of products.

frmPersonalInformation

comboBoxProducts, productsComboBox, cmbProducts

A RadioButton which tells if a person is male. radioButtonMale, maleRadioButton, radMale


A MenuItem for saving a file.

menuItemSave, saveMenuItem, mnuSave

A CheckBox to subscribe to newletter.

checkBoxSubscribe, subscribeCheckBox, chkSubscribe

The following lessons use the first naming convention where you simply use the name of the control in
camelCasing style followed by a descriptive name. You don't have to memorize a set of abbreviations or
invent one. When you drag a control from the ToolBox, you simply need to remove the number suffix and
add a descriptive name. When you are typing and you want to easily find what control you want to work
with, simply type what kind of control it is, for example, a text box, and all the text box controls will show
up in the IntelliSense. The only downside is some names might become too long. It is still up to you as to
what naming convention you are more comfortable to use.
The following gives you some example name depending on the control and its use.
It is not necessary to name every control in the form. Controls that will never be accessed in code can be
left by their default name. Examples of these are the labels that are merely used to label other controls.
Have a habit of naming the control after you place them onto the form.

The Windows Form


Windows Forms (or simply forms) are the windows you see in a Windows Application. You can create
multiple forms in a single application. Each form inherits the properties and methods of
the System.Windows.Forms.Form class. The namespaceSystem.Windows.Forms contains components
you will need for creating forms and controls.
The following are the parts of a typical windows form.

Property

Description

AcceptButton

The button on the form that is pressed when you hit the Enter key.

CancelButton

The button on the form that is pressed when you hit the Esc key.

ClientSize

Gets or sets the client area of the form. The client area is the portion of the form inside
the frame borders.

ControlBox

Specifies whether to show the control box at the top right portion of the form. The control
box contains the buttons minimize, maximize, and close.

Controls

A collection of Control objects contained inside the form.

DesktopBounds

The size and location of the form in the Window's desktop.

Font

The font that the form will use. Controls inside the form will inherit this property.

FormBorderStyle The border style of the form.


HelpButton

Shows a help button right before the close button of the form. (minimize and maximize
buttons should be disabled)

Icon

The icon that will be used by the form.

Location

The coordinates of the form in the screen.

MainMenuStrip

Specifies the main menu to be used by the form.

MaximizeBox

Tells whether the maximize box located at the top right is displayed.

MinimizeBox

Tells whether the minimize box located at the top right is displayed.

Modal

Tells whether the form is modal.

Name

The name of the form that is used to reference it in the code.

OwnedForms

A collection of forms that this form owns.

Owner

The form that owns this form.

ShowIcon

Tells whether the icon is displayed at the left side of the caption bar.

Size

The size of the form.

StartPosition

The starting position of the form when it is initially shown.

Text

The text that is shown in the caption bar of the form.

At the top, you will find the Caption Bar. The Caption Bar is composed of the icon, the caption, and the
control box. The control box contains buttons such as minimizing, maximizing, closing, or a help button.
The Client Area is where we

add the controls. The border or frame, which includes the caption

bar,encloses the client area and allows you to resize the form.
The following are some of the useful properties of the Form base class.
Figure 1

Figure 2 shows some useful methods of the Form class.

Method

Description

Activate

Gives the focus to this form and activates it.

AddOwnedForm

Adds a new form that this form owns.

CenterToScreen

Centers the position of the form in the screen.

Close

Closes the form.

Hide

Hides this form.

OnLoad

Raises the Load event.

Show

Shows the form.

Figure 2

Figure 3 shows the available events for the form.


Event

Description

Activated

Occurs when the form is activated.

Click

Occurs when the form is clicked.

Deactivated

Occurs when the form is no longer in focus.

FormClosed

Occurs after the form is closed.

FormClosing

Occurs when the form is closing. Allows you to halt the closing of the form.

HelpButtonClicked

Occurs when the help button is clicked.

KeyPress

Occurs when a key on the keyboard is pressed.

Load

Occurs when the form is finished loading just before it is displayed.

MenuComplete

Occurs when the menu of the form loses focus.

MenuStart

Occurs when the menu of the form receives focus.

ResizeBegin

Occurs when the form enters resizing mode.

ResizeEnd

Occurs when the form exits resizing mode.

Shown

Occurs after the form is shown for the first time.

Figure 3

The Form class is a child of the System.Windows.Forms.Control base class so the methods and
properties from the Control class are also available in the Form class.

Modifying the Control Box


We use the ControlBox property to hide or show the Control Box. This is useful when you are planning to
disable minimizing or

maximizing of control or you want to only close the form through the code. The

image below shows you how the form will look when you set ControlBox property to false.

If you want to disable only the minimize or the maximize button, then you can use
the MinimizeBox and MaximizeBox and set them to false.

The form above has its minimize and maximize box hidden. Unfortunately, you cannot hide only the close
button.

Changing Form's Border Style


We can change the border style of the form. For example, let's say you don't want the user to be able to
resize the form The default border of the form allow a
the FormBorderStyle

property

to

user to do that. We can set


different

values

of

the System.Windows.Forms.FormBorderStyle Enumeration.


Value

Description

None

The form has no border.

FixedSingle

The form has a non-resizable single line border.

Fixed3D

The form has a non-resizable 3d border.

FixedDialog

Sizable
FixedToolWindow

SizableToolWindow

The form has a thick, non-resizable, dialog style border that has no minimize
or maximize boxes.
The default. The form has a resizable border.
The form has a non-resizable border that has only a close button. This style is used for
tool windows.
Same as FixedToolWindow but resizable.

The following are screenshots of forms using different FormBorderStyle.

None

FixedSingle

Fixed3D

FixedDialog

Sizable

FixedToolWindow

SizableToolWindow

Form Icons
We use the Icon property to change the icon displayed at the upper left side of the form. Click the browse
button next the Icon property in the Properties Window and find the .ico file which is the file extension
for an icon image. The ShowIcon property allows you to hide or show the icon in the caption bar.

Accept and Cancel Buttons


You can add a button control to the form and set them as either an Accept or a

Cancel button. You do

that using the AcceptButton andCancelButton properties. If a button is an accept button, whenever the
user hits Enter while the form is active, that button's Clickevent will be executed. The Cancel button is
activated whenever the Escape key is pressed. Just go to the Properties Window, find the desired property
and click the drop down button. You

will be presented with the names of all the button control in the

form. Choose the desired button. For example, suppose you are creating a login form. You can

set the

button used for logging in as the Accept button. This way, the user can simply press Enter when he is
finished typing the password.
There are many more to discover on windows forms and they will be discussed in later lessons.

The Button Control


The Button control (System.Windows.Forms.Button) is commonly used to execute commands when it
is clicked. When a button is clicked, you specify codes that will be used. Buttons are typically used to
confirm or cancel an action, to perform different actions, and to open some more dialogs.
The Button control has several properties that you can use. The table below enumerates them.
Property

Description

AutoEllipsis Specifies whether to append dots (...) when the


can't fit the button.

text in the button is too long and

AutoSize

Specifies whether the button will automatically resize to fit its content.

FlatStyle

Determines the style of the button. Popup makes the button flat, and when you hover
on the button, the button will pop out. Flat makes the button flat and when you move
point your mouse inside the button, the background color of the button changes.

Enabled

If set to false, the button cannot be clicked or receive focus.

Image

An optional image that you can place inside the control.

ImageAlign

The alignment of the image in the button.

Text

The caption inside the button.

Visible

Tells whether the button is visible or not.

Figure 1 - Button Properties

Event

Description

Click

Occurs when you click the button.

Enter

Occurs when the control


active control of the form.

Leave

Occurs
when
inactive anymore.

LocationChanged

Occurs
when
the
button is changed.

MouseDown

Occurs when the mouse pointer is in the button


and the mouse button is pressed down.

MouseEnter

Occurs when the mouse enters the button.

MouseHover

Occurs when the mouse stays


in the button for an amount of time.

MouseUp

Occurs when you pressed the button and


you let go of the mouse button.

MouseLeave

Occurs
when
leaves the button.

the

the

becomes

control
location

mouse

the

becomes
of

the

stationary

pointer

A button is still useless by just editing its properties. It needs to react to events to do some work. The
following are the most common events available for the Button control.
You have already seen the Click event which is the default event for a button. Let's create another
application that demonstrates the use of other events. Create a new form and drag a button to the form
from the toolbox. It's not important what text you put for the button. In the properties window, find
the Name property and change its value to buttonSample. We will now refer to that button in the code
using that name. Our program will demonstrate the MouseEnter and MouseLeave events. To access these
events, the easiest way is to go to the properties window and click the button with the lightning symbol.

First, find MouseEnter and double click it. Visual

Studio will generate an event handler for you for that

specified event. Type the highlighted code inside the method.


private void buttonSample_MouseEnter(object sender, EventArgs e)
{
buttonSample.Text = "Mouse has entered!";
}

After typing the code, return back to the Properties Window and now choose the MouseLeave event and
double click it to generate an event handler. Again, type the highlighted code inside the event handler
method.
private void buttonSample_MouseLeave(object sender, EventArgs e)
{
btnSample.Text = "Mouse has left!";
}

Now run the program. Roll over your mouse to the button and notice that the text has changed. Take away
the mouse pointer from the button and the text of the button will change again.

The Label Control


The Label control (System.Windows.Forms.Label) is used to add text to a form that can be used to
show messages, or add labels to identify what other controls' functionality is. Drag a label control from the
toolbox to the form. By default, it will have an initial text. The following properties are the most common
ones that you will modify.

Property

Description

AutoSize

If true, the size of the borders of the label control


in the designer will be resized automatically
depending on the text inside it.

BorderStyle

Specifies the type of border around the label.

Font

Used to change the font


text inside the label control.

Text

The text of the label.

TextAlign

The alignment of the text inside the Label control

properties

of

the

The Text property is the most important one because the main purpose of the Label control is to show text
in the form.

Label1.Text = "Hello World!";


You can modify the Font property to change the font family, font size and many font properties.

There are events that are also available for the Label control, but most of the time, you won't be needing
them.

The TextBox Control

Property

Description

AcceptsReturn Used with Multiline. Tells if whether the return key is included in the input. The
return will be converted into a \n escape sequence.
AcceptsTab

Indicates whether to accept tab as an input. By default, hitting tab will bring the focus
to the control with the next TabIndex in the form.

Enabled

Set to false to make the text box read-only therefore making the text box act like a
label.

Font

The font properties that will be used by the textbox.

Lines

The lines of text in a multiline text box.

Multiline

Set to true to allow multiple lines in a text box.

Text

The text inside the text box.

PasswordChar

Accepts a character that will be used to mask each character typed by the user.

ReadOnly

Tells whether the text in the form can be edited.

Visible

Tells whether the text box is visible inside the form.

WordWrap

Used with Multiline. Set to true to enable automatic wrapping of words.

The TextBox control (System.Windows.Forms.TextBox) is the most basic means of input in a windows
forms. You give the input data by typing it inside the text box. The text you type can be accessed by using
the Text property of the control. The following table shows some useful properties that you can use for
the TextBox control.
Figure 1

The following example shows the use of text boxes. Create a new Windows Application project. The
program will ask two numbers and then when a button is pressed, the sum is shown using a label. Drag
two textboxes to the form and name them textBoxFirstNumberand textBoxSecondNumber. Also drag
one label for each text box indicating their purpose. Drag another label that will be used to show the sum
and name it labelSum. Place a Button control and name it buttonAdd. Adjust the position and sizes of the
controls to match the layout below.

Double-click the button to add an event handler to its click event. Type the following codes.
private void buttonAdd_Click(object sender, EventArgs e)
{

int num1 = Int32.Parse(textBoxFirstNumber.Text);


int num2 = Int32.Parse(textBoxSecondNumber.Text);
int sum = num1 + num2;

labelSum.Text = "Sum = " + sum;


}

The code converts the contents of textBoxFirstNumber and textBoxSecondNumber into integers using
the Parse method of the Int32class and stored them in their respective variables. We require conversion
because the Text property is of type string. Their contents are accessed using the Text property. The
sum is then determined. The sum is displayed afterward by assigning it to the Text property oflabelSum.
The most useful event of the TextBox is the TextChanged event which occurs when the text inside the
textbox is modified. The following program shows an example of using this event.
Create another windows forms application and add a textbox and a label in the form. Name them you can
leave their default names right now.

Delete the text of label1 by removing the content of its Text property. Note that it would be hard to
select this label now if the AutoSizeis set to false so you can select this label using the top combo box of
the Properties Window. The default event of the TextBox control is the TextChanged event so double
clicking it will create an event handler for the said event. Add the following code to the event handler.
private void textBox1_TextChanged(object sender, EventArgs e)
{
label1.Text = textBox1.Text;
}

Now run the program and type anything in the text box. Notice that the text of the label copies the text
you type in the text box.

When the text inside the textbox is modified, the event handler executes and copies the text inside textbox1
to label1.
By default, a text box can only handle a single line of text. To make it a multiline textbox, simply set
the Multiline property to true. Once you do that, you will notice that you can change the height of the
textbox in the designer.

You can set the WordWrap property to true to automatically bring the cursor below when it reaches the
right edge of the text box. If it is set to false, the text will continue to the to the right clipping the ones at
the left side. You can set the ScrollBar property to Horizontal,Vertical or Both to add scroll bars to
a multiline text box. When using a multiline textbox, you can use the Lines property to retrieve the
individual lines of text.
If your textbox is expected to accept passwords, then you must set the PasswordChar to something
like * to mask each character type in the textbox by the character indicated in the PasswordChar property.

You might also like