clase 04 (aplicaciones graficas)
DESCRIPTION
Aplicaciones GraficasTRANSCRIPT
Página 1
Drawing en C Sharp
Página 2
C# Object Oriented Programming
Hasta ahora, en C # Esenciales hemos analizado los conceptos básicos de la programación en C #,
como los tipos de variables y control de flujo. Aunque sería posible escribir un programa funcional
utilizando estas técnicas, hay mucho más para convertirse en un programador competente C #. C # es,
ante todo, un lenguaje orientado a objeto y, como tal, cualquier programador de C # se prevé la
creación de aplicaciones orientadas a objetos utilizando este idioma.
C # proporciona un amplio soporte para el desarrollo de aplicaciones orientadas a objetos. El tema de
la programación orientada a objeto es, sin embargo, de gran tamaño. No es una exageración afirmar
que libros enteros se podría dedicar a la materia (porque los libros enteros se han dedicado al tema).
Como tal, una descripción detallada del desarrollo de software orientado a objetos está más allá del
alcance de C # Es-sentials. En su lugar, vamos a introducir los conceptos básicos que intervienen en
la programación orientada a objetos y luego pasar a explicar el concepto que se refiere al desarrollo
de aplicaciones C #.
¿Qué es un objeto?
Un objeto es una pieza autónoma de la funcionalidad que se puede utilizar fácilmente, y volver a uti-
lizarse como bloques de construcción para una aplicación de software.
Los objetos consisten en variables de datos y funciones (llamados métodos) que se puede acceder y
pidió al objeto de realizar las tareas. Estos se denominan colectivamente como miembros.
¿Qué es una clase?
Así como un plano o dibujo del arquitecto define lo que es un elemento o un edificio se verá como
una vez que se ha construido, una clase define lo que un objeto se verá como cuando se crea. Se de-
fine, por ejemplo, cuáles son los métodos de hacer la voluntad y cuáles son las variables miembro
será.
Declarar una clase de C #
Antes de que un objeto puede ser instanciada primero tenemos que definir «modelo» de la clase para
el objeto. En este capítulo vamos a crear una clase de cuenta bancaria para demostrar los conceptos
de la programación orientada al objeto C #.
Una C sharp clase se declara utilizando las palabras clave public class seguida del nombre de la clase.
Aunque el compilador de C # aceptará casi cualquier nombre para una clase, programación conven-
ción dicta que un nombre de clase comienzan con una letra mayúscula:
public class BankAccount
{
Página 3
}
We have now defined a class which currently contains no members. The next task, therefore, is to add
some members.
Creating C# Class Members
Los miembros del grupo o propiedades son esencialmente variables y métodos incorporados en la
clase. Miembros pueden ser públicos, privados o protegidos. Métodos del público se puede acceder
desde fuera del objeto y también son visibles en las clases derivadas de la clase actual. Métodos
privados sólo se puede acceder por los métodos que figuran en la clase y no son accesibles a las clases
derivadas. clases protegidas sólo están disponibles para las clases derivadas.
Esta es la clave para lo que se denomina encapsulado de datos. Convenciones programación orientada
a objetos Dicstados que los datos deben ser encapsulados en la clase y acceder y configurar sólo a
través de los métodos de la clase (normalmente llamado getters y setters).
Ahora podemos extender nuestra clase CuentaBancaria para agregar variables miembro para contener
el nombre y número de cuenta. Fiel al concepto de encapsulación de datos vamos a hacer algunos de
estos miembros privados y los métodos de escritura para acceder a estos valores más tarde:
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
}
Now that we have defined the properties of our class we need to look briefly at a few additional data
member types, and then learn how to create object instances from the class.
Static, Read-only and Const Data Members
In addition the data member types we have looked at so far, C# also provides support for a number of
additional member types.
C# static member types (also referred to as class properties) are used to store data values which are
common to all object instances of class. For example, all bank customers would likely earn the same
rate of interest on a savings account. An interestRate member would, therefore, be declared as static
since it is common across all object instances of the class.
Página 4
Static members are declared using the static keyword. For example:
public class BankAccount
{
public static int interestRate;
}
Static members are accessed through the class, not though the object. For example we would change
the interestRate member for all object instances by reference the BankAccount class as follows:
BankAccount.interestRate = 10;
For data members that must not be modified the const and readonly keywords are provided by C#.
Both achieve the same objective of preventing the value assigned to a data member from being
changed after it has been declared. The value of a const or readonly member must be assigned at
creation time:
public readonly daysInWeek = 7;
Instantiating an Object from a C# Class
The process of creating an object from the class 'blueprint' is called instantiation. The first step is to
create an object variable of the required object type. An instance of the object is then created using
the new keyword and assigned to the object variable:
BankAccount custAccount;
custAccount = new BankAccount();
It is also possible to declare the object variable and assign the object in a single statement:
BankAccount custAccount = new BankAccount();
Now that we have an instance of our BankAccount class the next step is learn how to access the
members of the class.
Accessing C# Object Members
Now that we know how to write a class and instantiate objects from the class, we now need to know
how to access the members of the object. Firstly, you will recall that we declared some members as
being public and others as being private. The public methods are fully accessible from outside the
object. This is achieved using something called dot notation. Dot notation is a mechanism by which
object members may be accessed by specifying the object and member names separated by a dot (.).
For example, to access the accountName member of an object named custAccount we would reference
this member using custAccount.accountName:
Página 5
using System;
class Hello
{
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
}
static void Main()
{
BankAccount custAccount = new BankAccount();
custAccount.accountName = "John Smith";
custAccount.accountFee = 5;
Console.WriteLine ("Customer Name is " + custAccount.accountName);
Console.WriteLine ("Account Fee = $" + custAccount.accountFee);
}
}
The above code assigns values to the accountName and accountFee members of our object. It then
references the properties in order to display text which reads:
Customer Name is John Smith
Account Fee = $5
This approach works well for public class members, but not for private members. An attempt, for
example, to use dot notation to access the private accountNumber member will result in a compilation
error along the the lines of:
error CS0122: 'Hello.BankAccount.accountNumber' is inaccessible due to its protection level
In order to access private members we need to provide access methods in the class.
Adding Methods to a C# Class
Página 6
Class method members are sections of code contained in a class which can be called from outside an
object to perform specific tasks. Common types of methods are getter and setter methods which are
used to access private data members of a class. For example, we can declare a getter and a setter
method to get and set the protected accountNumber member:
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
public int getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(int newNumber)
{
accountNumber = newNumber;
}
}
Class methods are called using dot notation. For example, to set the value of the accountNumber:
BankAccount custAccount = new BankAccount();
custAccount.setAccountNumber( 12345 );
Console.WriteLine ("Account Number = " + custAccount.getAccountNumber() );
The above code sets the account number using the setter method and then displays the account number
using the getter method.
Now that we have looked at method class members the next task is to look at two special class meth-
ods, constructors and finalizers.
C# Constructors and Finalizers
Despite the grand sounding names, C# class constructors and finalizers are nothing more than methods
which get called when an object is instantiated and destroyed. The constructor is particularly useful
for allowing initialization values to be passed through to an object at creation time. Let's say that we
Página 7
would like to be able to initialize the accountName and accountNumber members at the point that we
initialize the custAccount object. To do so we need to declare a constructor.
Constructors are declared the same way as other methods with the exception that the name of the
method must match the class name:
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
// Constructor
public BankAccount(string acctName, int acctNumber)
{
accountName = acctName;
accountNumber = acctNumber;
}
// ....
}
We can now use the constructor to initialize these members at object creation:
BankAccount custAccount = new BankAccount("Fred Wilson", 123456);
Finalizers are used to clean up any resources used by a class object when the object is destroyed.
Unlike constructors which can be triggered from code using the new keyword there is no way to
explicitly call a finalizer (for example there is no delete equivalent to the new keyword). Instead, the
finalizer will be called when the garbage collector decides that the object instance is no longer needed.
All the programmer can be sure of is that the finalizer will be called at some time between the when
the object is no longer needed by the code and the point that the application terminates.
Finalizers are defined in the same way as constructors with the exception that the name is preceded
by a tilde (~):
// Finalizer
public ~BankAccount(string acctName, int acctNumber)
{
// Code to perform clean up
}
Página 8
C# Inheritance
In C# Object Oriented Programming we looked at the basics of object oriented programming in C#.
Now that we have covered these basics the next topic to be covered is that of class inheritance.
What is Inheritance?
The concept of inheritance brings something of a real-world view to programming. It allows a class
to be defined which has a number of characteristics and then other classes to be created which are
derived from that class. The derived class inherits all of the features of the parent class and typically
then adds some features of its own.
By deriving classes we create what is often referred to as a class hierarchy. The class at the top of the
hierarchy is known as the base class and the derived classes as subclasses. Any number of classes may
be derived from a class. It is only possible for a derived class to inherit from one class. As such, C# is
known as a single inheritance programming language.
Classes need not only be derived from a base class. For example, a subclass can also inherit from
another subclass.
An Example of Inheritance
As with most programming concepts the subject of inheritance in C# is perhaps best illustrated with
an example. In the previous chapter we created a class called BankAccount:
public class BankAccount
{
public string accountName;
public int accountFee;
private int accountBalance;
private int accountNumber;
public int getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(int newNumber)
{
accountNumber = newNumber;
}
Página 9
}
This class does a good job of defining characteristics common to any type of bank account, such as
account holder name, account number and current balance. Imagine, however, that our banking pro-
gram needs to support a number of specific types of account. For example, the bank might offer its
customers an interest bearing savings account. A savings account will have all the characteristics of
our BankAccount class but would also need a way to store the prevailing interest rate. One option
would be to create a brand new class from the ground up called SavingsAccount which duplicates
everything we have in our BankAccount class, plus extra members needed for a savings account.
Another, more efficient method is to derive a SavingsAccount class from the BankAccount class and
then add in the extra functionality into this subclass.
Creating a Subclass in C#
Now that we have ascertained that we need to create a sub class of our BankAccount class we can
take a look at the code necessary to achieve this. Subclasses are declared in the same way as any other
class with the exception that the class name is followed by a colon (:) followed by the name of the
class from which it is to inherit. With this in mind we can begin by creating our SavingsAccount class:
public class BankAccount
{
public string accountName;
public int accountBalance;
public int accountNumber;
public BankAccount (string name, int number)
{
accountName = name;
accountNumber = number;
}
public int getAccountNumber()
{
return accountNumber;
}
public void setAccountNumber(int newNumber)
Página 10
{
accountNumber = newNumber;
}
}
public class SavingsAccount : BankAccount
{
}
We have now created a sub class of BankAccount called SavingsAccount, but at this point the Sav-
ingsAccount class is no different than its parent class. Next we need to add some new members to add
the behavior we need:
public class SavingsAccount : BankAccount
{
public double interestRate;
public SavingsAccount (string name, int number, int balance, double rate)
: base (name, number)
{
accountBalance = balance;
interestRate = rate;
}
public double monthlyInterest()
{
return interestRate * accountBalance;
}
}
We now have a new class called SavingsAccount which inherits all the members of the BankAccount
class and adds some members of its own. In particular we have added a new data member called
interestRate which will store the interest rate paid on the account together with a new method to
calculate the monthly interest.
Passing Arguments to the Base Class Constructor
Of particular significance is the constructor. In the BankAccount base class we have a constructor
which takes the account name and account number as arguments. In the SavingsAccount subclass we
need to accept two additional arguments - the balance and the interest rate. The : base code instructs
C# to handle the name and number arguments using the constructor from the base class. The remaining
two arguments are then passed to the SavingsAccount constructor.
Página 11
With our subclass complete we can now make use of it:
static void Main()
{
SavingsAccount saveAccount = new SavingsAccount("Fred Wilson", 123456, 432, 0.02F);
Console.WriteLine ("Interest this Month = " + saveAccount.monthlyInterest() );
}
C# and Windows Forms
The Windows Form is a vital component in the development of any Windows-based application.
Forms essentially provide the windows that make up a Windows application. In fact, the terms win-
dow and form are often used interchangeably. Forms allow the C# developer to create windows and
layout controls (such as buttons, labels etc) in those forms to provide the application's user interface.
In the next chapter (Designing Forms in C# and Visual Studio) we will look at how to layout controls
inside a form. Before we reach that stage, however, there are a surprising number of ways in which
the form itself can be modified and configured. We will cover these options in detail in this chapter.
Creating a New Form
Throughout this chapter we will work with a form in a new project. Begin by starting Visual Studio
and creating a new Windows Application project. Name the project CSharpforms.
Once the new project is created you will see a new Form in Visual Studio ready for you to begin work.
Changing the Form Name
All GUI objects in a C# application need a name so that they can be referenced in the C# code. When
a new object is added to an application in Visual Studio it is assigned a default name which usually
consists of the object type and a number. For example the first form object in an application is named
Form1, the second Form2, and so on.
To change the name of a Form to something more meaningful, simply click in any area of the Form
in Visual Studio and change the (Name) value in the Properties panel.
Changing the Form Title
Página 12
Each form in Visual Studio repre-
sents an application window in the
finished C# based application.
The text displayed in the title bar
for each window should be
changed to display something
meaningful. This should either be
the name of application, or a de-
scription of the form's function
(for example Order Entry or Save
File).
The value of the text to be dis-
played in the window title is de-
fined by the selected form's Text
property. To change the title of the
form, therefore, select the Text
value in the Properties panel (located by default in the bottom right hand corner of the Visual Studio
main window) and change it to a new value (for example, 'C# Form Example'):
Changing the Form Background Color
The background of any form may be changed either by specifying a new color, or by using a back-
ground image. The background color is controlled by the BackColor property of the form. By default
this property is set to Control. This specifies that the form should use a system defined default color.
This color varies between different Windows versions, and changes when the user changes the overall
color scheme of their Windows system.
To change the background color, select the form in Visual Studio and locate the BackColor property
in the Properties panel. There are a number of ways to specify a color.
Color by name - Simply type in a color name into the BackColor value field (for example Red,
Yellow, Cyan etc).
Color by RGB value - Colors may be specified by entering the hexadecimal RGB values (for
example #FFFFFF for white, #000000 for while and so on). RGB values may also be specified
using decimal values (for example 255,255,255 for white, 0,0,0 for black etc).
Color from existing palette - Clicking on the down arrow in the BackColor value field will
display a drop down menu. Lists are available for web safe colors, custom colors and system
colors.
Once you have selected a new color the background color of your form will change to reflect the new
setting.
Página 13
Changing The Form Background Image
In addition to changing the background color of a form, it is also possible to specify a background
image. This is specified using the form's BackgroundImage property in the Properties panel. When
the BackgroundImage property is selected in the Property panel a button containing the label '...'
appears. Click on this button to display the Select Resource window:
Click on the Local Resource op-
tion button and click on Import to
browse for an image. If you don't
have any images of your own
readily available try looking in for
the Sample Pictures folder in My
Documents.
Once selected, the image will be
applied to the form background
and any controls added will ap-
pear on top of the image. The fol-
lowing figure shows a form with a
background image and a Button
control:
If the image used for the back-
ground is smaller than the form
size, windows will use multiple
copies of the image in a tile ar-
rangement to ensure the entire
available area is filled.
Configuring the Minimize, Maximize and Close Buttons
Página 14
Each window in a Windows application has, by default, Minimize, Maximize and Close buttons in
the top left hand corner of the title bar. In addition, clicking on the icon on the right hand side of the
title bar drops down a control box containing the same options, plus options to resize the window.
These options make it easy for the user to perform tasks such as minimizing or maximizing a form. If,
however, you do not want these controls to be available for a particular form they can be disabled
from the Properties panel for the form in question. To disable the Maximize button set the Max-
imizeBox property to False. Similarly, disable the Minimize button by setting the MinimizeBox prop-
erty to False. In each case the button will still be visible, but will be disabled so the user cannot click
on it.
To remove all controls, including the Control Box and the Minimize, Maximize and Close buttons set
the ControlBox property to false. When set, the only content in the form's toolbar will be the form
title.
Setting Minimum and Maximum Form Sizes
The minimum and maximum sizes of a form can be specified. These limitations are controlled via the
MinimumSize and MaximumSize properties respectively. Once set, assuming the form is sizable, the
user will not be able to resize the form beyond the size boundaries you have defined using these
properties.
Specifying the Position of a Form on the Display
The initial position of a form when it is first displayed in an application is controlled by the form's
StartPosition property in conjunction with the Location property. The StartPosition property can be
set to one of a number of different values:
Manual - Sets the initial position of the form to the X and Y coordinates specified by the
Location property.
CenterScreen - Specifies that the form should be positioned in the center of the display.
WindowsDefaultLocation - This is the default setting for this property and dictates that the
form be positioned in the default Windows location for new windows (typically near the top
left hand corner of the screen).
CenterParent - If the form is a child of another form, this value specifies that the form should
be positioned within the center of the parent form.
Changing the Form Border
By default a form can be resized by the user. Visual Studio allows both the behavior, and the appear-
ance of the border to be controlled by manipulating the FormBorderStyle property. The border may
be configured to allow, or disallow resizing of the form, with a variety of border styles (such as 3D).
Página 15
To change the border, select the FormBorderStyle in the Properties panel of the form you wish to
modify. Click on the down arrow in the value field to drop down a menu of items and select the setting
of your choice. Feel free to experiment with the different settings, using the F5 key to build and run
your application to try out each setting.
Stopping a Form from Appearing the Windows Taskbar
By default every form in an application is shown in the Windows desktop taskbar when it is created.
Whilst this is acceptable for a small application consisting of one or two forms, it is unlikely that you
would want every single form to appear in the taskbar.
To prevent a form from appearing the taskbar simply set the ShowInTaskbar property to False.
Creating a Transparent Form
The Opacity property can be used to control the degree of transparency of a form of control. The lower
the opacity percentage, the more transparent the form or control. To make a form transparent, select
the form and change the Opacity percentage to 70% (if you select a percentage that is too low the
form will be invisible when the application is run). Press F5 to build and run the application. The form
will be partially transparent in that you can still see the form and its controls, but you can also see
what is on the desktop behind the form.
Designing Forms in C# and Visual Studio
A primary job of a C# programmer is the development of graphical Windows based applications.
Given this fact, it is not surprising that an important part of developing with C# and Visual Studio
involves the design of Windows Forms. In this chapter of C# Essentials, we will cover in detail the
design of Forms using Visual Studio.
Visual Basic Forms and Controls
The form object is essentially a container for holding the controls that allow the user to interact with
an application. Controls are individual objects such as Buttons, Toggles and TextBoxes. In C# and
Windows Forms we looked at the many options for configuring a Windows Form. In this chapter,
however, we will cover the steps involved in laying out controls on a Form in Visual Studio.
When a new Windows Application project is created in Visual Studio the first object you will see is a
form. Typically it will appear in the design area as follows:
Página 16
Controls are added to the form us-
ing the Toolbox. The Toolbox is
usually accessed by clicking on
the Toolbox tab to the left of the
Visual Studio main window. The
Toolbox can be pinned in place so
that it no longer auto-hides by
clicking on the push pin in the title
bar. It can also be detached and al-
lowed to float anywhere on the
desktop by clicking and dragging
on the title bar after applying the
push pin. When detached, the
Toolbox appears as follows:
Visual Studio provides three
methods for adding new controls to a form. In this chapter we will cover each of these different
approaches.
Double Clicking the Control in the Toolbox
The Toolbox contains all of the controls available to be added to a form. One way to add a control to
form is to simply double click on the control in the Toolbox. The control is then automatically added
to the current form. The advantage of this approach is that it is very quick to add multiple controls to
a form. The downside is that Visual Studio does not know where you want the control positioned in
the form and consequently positions the controls near to the top left hand corner of the form. Once the
control is added to the form you will need to click and drag it to the desired location.
Dragging a Dropping Controls onto the Form
Another approach to adding controls to a form is to click on the control in the Toolbox and drag it
onto the form. When the control is in the required location, release the mouse button to drop the
control into place. The position of the control can subsequently be refined using the mouse or arrow
keys to move the location of the control.
Página 17
Drawing a Control on the Form
The most precise mechanism for adding a control to a form is to draw
it. This is achieved by first selecting the desired control in the
Toolbox. Once the control is highlighted, move the mouse pointer to
the location on the form where you would like the top left hand corner
of the new control to appear. Click and hold down the left hand mouse
button a drag the pointer. A box will be drawn as you drag the pointer.
When the box reaches the required size for the new control, release
the mouse button. The new control will appear positioned and sized
according to the size and location of the box.
Positioning and Sizing Controls Using the Grid
When adding controls to a form it is possible to configure how con-
trols are positioned and sized by activating a grid. When the grid is
active, controls "snap" to the nearest grid position when added to a
form.
There are a number of ways to configure the granularity and behavior
of the Visual Studio grid. These settings are global in that, once de-
fined, they apply to all forms and projects, not just to the current form
or project. Note also that for some reason, changes to the grid do not
immediately take effect in forms in which you are already working.
Grid settings are changed using the Visual Studio Options screen. To access this screen, select Op-
tions... from the Tools menu. When the dialog appears, click on Windows Forms Designer in the left
hand tree. Once selected the dialog should appear as follows:
The settings available here require
some explanation:
GridSize - This setting controls
the vertical and horizontal dis-
tances between the grid points on
the form. This essentially controls
the granularity of the grid. The
smaller the gaps between grid
points, the greater control over
control size and position.
ShowGrid - Controls whether
the grid dots are visible in the
Página 18
form. Note that this setting controls only whether the grid is visible, not whether controls snap
to the grid locations. Snapping is controlled by the SnapToGrid setting.
SnapToGrid - This setting determines whether the grid is used when controls are added. When
set to True new controls will "snap" to the nearest grid location when added. When set to False
the grid is ignored and controls will appear where they are dropped or drawn.
LayoutMode - Controls whether controls are laid out by snapping to a grid location, or are
aligned with other controls in the form. Aligning with other controls is achieved using "Snap
Lines" which are covered in detail in the next section of this chapter.
Spend some time changing the settings and adding new controls or move existing form controls. In
particular, try different GridSize and SnapToGrid settings.
Positioning Controls Using Snap Lines
One of the key objectives in designing esthetically pleasing forms is getting controls aligned. One
way to make the task of aligning controls involves the use of "Snap Lines" in Visual Studio. When
activated, the Snap Lines feature causes a line to be drawn between an edge of the control you are
currently moving and the corresponding edge of the closest control on the form when the edges are in
alignment.
To active Snap Lines select Options... from the Tools menu, click on Windows Form Designer in the
tree to the left of the Options dialog and configure the following settings:
Layout Mode: SnapLines
SnapToGrid: False
ShowGrid: False
Once the settings are applied, add a Button control to a form. Next, click on the ListBox control in the
ToolBox and drag it over to the form. As you move the ListBox below the Button a line will appear
between the controls at any point that edges align. For example the following figures show a line
appearing at the point the left and right hand edges of the controls align:
Página 19
Selecting Multiple Controls
It is often useful to be able to select multiple controls in a form. Normally when you click on one
control in a form, the currently selected control is deselected. There are two ways to select multiple
controls. One method is to hold down the Shift key while selecting controls. With the Shift key pressed
any currently selected controls will remain selected while other controls are clicked.
Another method is to rubber band the controls. To do this click on any empty area of the form to the
top left of the group of controls you wish to select. With the mouse button depressed drag to draw a
box around the controls. When you release the mouse button all the controls within the box area will
be selected.
To de-select individual controls from a group of selected controls, simply hold down the Shift key and
click with the left hand mouse button on the control to de-select.
Once a group of controls are selected you can move all the controls at once, maintaining their positions
relative to each other, simply by clicking and dragging the entire group.
Now that we have covered selecting groups of controls we can now look at some other tasks that can
be performed on groups in Visual Studio.
Aligning and Sizing Groups of Controls
Visual Studio provides a number of tools to assist in aligning groups and sizing groups of controls in
a form. These features are accessed using the layout toolbar. To display the layout toolbar right click
on any part of the standard Visual Studio Toolbar and select Layout from the drop down menu. The
resulting toolbar will appear as follows:
Página 20
Select a group of components and click on the various buttons in the toolbar to see the effect. For
example, all the controls can be left or right aligned and resized to the same size, width or height. It is
also possible to equally space the controls, and then increase or decrease the spacing used to separate
the controls. It is also possible place controls on top of one another and change which control appears
on top of the stack (this can also be done in C# code using the BringToFront() and SendToBack()
methods of the respective controls).
All together, the range of options allows just about any uniform layout to be achieved from a group of
controls in a form.
Setting Properties on a Group of Controls
In addition to changing the size and layout of a group of controls it is also possible to set properties
simultaneously on the group. When multiple controls are selected as a group the Visual Studio Prop-
erties panel changes to list only the properties which are common to all the control types comprising
the group. Changing a property value in the properties panel applies that change to all selected con-
trols.
Anchoring and Autosizing Form Controls
All the controls we have worked with so far have been a fixed size. They have also remained that
same size, even if the form in which they reside is resized. It is often useful to have a control resize
when the form is resized. This is achieved using the Anchor property. To use this property, select a
control in a form and click on the down arrow in the value field of the Anchor property in the Proper-
ties panel. A graphic will be displayed indicating the anchors currently set (typically the top and left
edges of the control). Activate the anchors on the right and bottom edges of the control to anchor those
sides:
Página 21
Once the anchors are in place,
press F5 to compile und run the
application. When the form is dis-
played and resized, the control
with the anchors will grow in pro-
portion to the size of the form.
Setting Tab Order in a Form
Despite the advent of the graph-
ical user interface and the mouse,
it is still common for users to nav-
igate forms using the keyboard.
The standard keyboard navigation
technique involves the use of the
Tab key to move from one control
to the next in a form. For this rea-
son it is vital that the Tab Order be configured to implement a sensible sequence of moves between
controls.
To view and change the current tab order for a form, display the Layout toolbar (if this is not already
visible, right click on the standard Visual Studio toolbar and select Layout). On the Layout toolbar
click the Tab order button (usually the last button on the right). The form will be displayed with a
number next to each control:
To change the order, simply click on each control in
the order you wish for them to be navigated by the tab
key. As you click on each control the number will
change, starting at 0 until all the controls have been
sequenced. The tab order is now set.
Understanding C# GUI Events
In the days before graphical environments such as Mi-
crosoft windows, applications were developed using a
procedural approach. This meant that the path a user
would take through an application was dictated by the
programmer at the point the application was developed. For example, the application might display a
Página 22
menu listing several options, and prompt the user to select an option. Depending on the user's selec-
tion, the application might display a data input screen in which data would need to be entered in the
order in which the fields were displayed on the screen. Once the data was entered the user would then
be able to press a key to save the data and return to the menu screen again.
The world of the graphical user interface is very different from the old days. Today a user is presented
with windows containing multiple controls such as buttons, text fields, toggles and sliders. The mouse
allows the user to interact with any of the visible controls in any order they choose. The programmer
can, therefore, no longer dictate the path a user will take through an application. A new way of han-
dling the interaction between a user and an application was needed. This approach is known as event
handling.
Instead of a procedural approach to programming, applications are now event driven. In essence, the
developer defines what the user interface is to look like, and then defines subroutines which will be
called when particular events are triggered. For example, the C# programmer might create a Form
containing a number of Buttons. For each Button, the programmer will define the C# code to be
executed when a Click event is triggered on each button. When the application runs, an event loop sits
in the background and waits for an event to be triggered in the application. Once an event is triggered
(such as button click or a keystroke in a text field) the event loop looks at the object from which the
event was triggered to see if an event handler has been defined by the developer for that particular
event type. If a handler has been defined, that subroutine is executed and the event loop continues to
loop waiting for the next event to be triggered.
Event Triggers
There are a number of ways events can be triggered:
User Interaction - One of the most common ways for events to be triggered is through user
interaction with controls in a Form. Each control has a number of events which can be trig-
gered. For example, a text field can trigger an event when a user types a character or when a
user moves the mouse over the control.
Object Event Triggering - Objects can trigger their own events. For example, the Timer object
can be configured to trigger its own Timer event after a specified amount of time has elapsed.
Operating System - The Windows operating system can trigger events which can be handled
by the application. For example, Windows will trigger an event when part of a window is
obscured by another window. In this situation C# receives an event when the previously ob-
scured window area is re-exposed so that it knows to repaint the area.
Programmatically triggered events - The event of any object may be triggered by the program-
mer from within the C# code. For example, a program may need to simulate the event triggered
by a user clicking on a button.
Página 23
Wiring Up Events in Visual Studio
In this section we will look at the steps involved in configuring events on controls in a Form. Create
a new Windows Application project in Visual Studio called CSharpEvents.
In this example we are going to create a Form containing a TextBox, a Label and a Button. We are
then going to set up event handlers such that any text typed into the TextBox will appear in the Label
control. We will also wire up an event handler on the Button to close the application when the button
is pressed.
The first step is to design the Form. Using the Toolbox (see Designing Forms in C# and Visual Studio
for an overview of designing forms) add a TextBox, Label and Button to the Form so that form appears
as follows:
Select each control in turn and using the Properties panel change the
Name of the controls to myButton, myLabel and textInput respectively.
The Form design is now complete and we can now begin to connect the
events to event handlers.
We will begin by defining an event procedure for the TextBox. To ac-
cess the textInput control event procedures simply double click on the
TextBox control in the Form. Visual Studio will subsequently display
the event procedures for the textInput control. By default Visual Studio
picks the most common event, the TextChanged event, and creates a
stub of the subroutine to be called when that event is triggered by the user.
In our example we want every keystroke performed by the user in the TextBox to be displayed by the
Label control. In this case the TextChanged event is exactly the event we want.
With the TextChanged event still selected it is time to write the C# code that will be executed when
the event is triggered. To do so, we will need to set the Text property of the myLabel control to equal
the Text property of the textInput control. The properties of objects are accessed using what is called
dot notation. For example the Text property of myLabel is accessed in C# code as follows:
myLabel.Text
To modify the event procedure, therefore, the code for this event needs to be modified as follows:
private void textInput_TextChanged(object sender, EventArgs e)
{
myLabel.Text = textInput.Text;
}
Página 24
Visual Studio, of course, makes life easy for us when accessing properties of objects. At the point that
you type the '.' after myLabel a drop down list of properties available with this type of object is dis-
played from which to choose. Either select the Text property from the list, or continue to type the word
Text. Repeat this for the textInput property
The implementation of the TextChanged event handler for our inputText control is now complete.
Now we need to implement the event procedure for the Button. Return to the form design by clicking
on the Form1.cs tab above the code editing area and double click on the myButton component to
access the code behind the button. This time the event we need to catch is the Click event. Once again,
Visual Studio anticipates out needs and takes us to the myButton_Click() event code.
Modify the event procedure to call Close() as follows:
private void myButton_Click(object sender, EventArgs e)
{
Close();
}
Now, when the button is pressed the application will exit.
Compile and Running the Application
Finally, build and run the application by pressing the F5 key or clicking on the Debug button in the
toolbar (the button displaying the green Play triangle). The application should compile and run. When
you type text into the TextBox the characters should also appear in the label:
Clicking the Button should close the application as specified in the Click() event procedure.
Setting Up a C# Timer Event
At the beginning of this chapter we mentioned that objects can trigger their own events. So far we
have only looked at events triggered by user interaction with the application's user interface. We will
now look at configuring the Timer object to trigger its own events. The first step is to add a Timer
object to our application. First, display the Toolbox if it is not already visible, unfold the Components
Página 25
section of the Toolbox list and scroll down until you find the Timer object. To add a Timer to the
application simply double click on it. Because the Timer is not a visible object it appears in a special
area beneath the Form as shown in the following figure:
With the Timer object selected,
use the Properties panel to change
the Enabled property to True and
the Interval property to 10000
(which will cause the Timer to
trigger a Tick event every 10 se-
conds). Next double click on the
Timer object to edit the event pro-
cedure. The Timer object has a
single event, the Tick event, which
is triggered each time the timer in-
terval elapses. We are going to
write code to set the myLabel con-
trol to display Your time is up
when the Tick event triggers:
private void timer1_Tick(object sender, EventArgs e)
{
myLabel.Text = "Your time is up";
}
Build and run the application and notice that after 10 seconds the label text changes to "Your time is
up". Enter some text into the TextBox so that the Label text changes again and wait 10 seconds. Once
again, the Timer will trigger the Tick event and the Label text will change.
Creating Top-Level Menus in C#
Since it is almost impossible create an application without needing a menu of some sort, this chapter
is dedicated entirely to the topic of creating top-level menus. The next chapter will cover Creating
Context Menus in C#. As you will see as we work through this topic, C# combined with Visual Studio
make the creation of menus extremely easy.
Creating a Top-Level Menu
Página 26
Top-level menus (the type of menus that run across the top of forms) are created using the Menu Strip
control. The first step in creating a menu, therefore, is to add a Menu Strip control to the form. With
your Visual Studio project loaded, and the Form to which you wish to add the menu selected, double
click on the Menu Strip control in the Menus and Toolbars section of the Visual Studio Toolbox. You
will notice that the Menu Strip object is added to the panel beneath the form, and that a Type Here
field appears at the top of the form as follows:
Use the Properties panel to change
the name of the Menu Strip object
to mainMenu. Click in the Type
Here field at the top of the form
and enter &File. This as the effect
of creating a menu item object la-
beled "File". The ampersand (&) is
added to instruct C# to use the 'F'
at the beginning of the file as the
accelerator key for this menu item.
As such, pressing Alt+F when the
application is running will be
equivalent to clicking on the menu
item with the mouse pointer. The
location of the ampersand in the
menu item Text property dictates
the accelerator key. For example
H&elp will declare 'e' as the accel-
erator for this particular men item.
Windows indicates the accelerator
for a menu item by underlining the letter (as you will see by the underlined 'F' on your File menu
item).
Once the File menu item has been added, Visual Studio will create both a drop down menu and a field
to add another menu item as follows:
Página 27
Click on the Type Here field and
type &Open File.... When you
have entered this text Visual Stu-
dio will add another Type Here
field beneath the "Open File" en-
try. Click in this field and enter
&Read File.... Once again, Visual
Studio provides the opportunity to
add another item. This time, how-
ever, we are going to add a differ-
ent type of item to the menu. As
you move the mouse pointer over
the Type Here field, the field will
highlight and a down arrow will
appear to the right of the Type
Here text. Clicking on this arrow
drops down a menu of items to
add to the menu:
The options available are as follows:
Página 28
MenuItem - Creates a sub-menu (also known as a pull-right menu) which essentially pops up
a new menu to the right of the currently displayed menu.
ComboBox - Adds a ComboBox control to the menu. Although you have the option of adding
a ComboBox to your menu, you should resist the urge to do so. The placing of a ComboBox in
a menu is not considered to be good user interface design.
Separator - Places a separator after the last menu item to be added. Separators in menus are
useful for distinguishing between groups of menu items.
TextBox - Adds a TextBox control to the menu. As with the ComboBox, you should resist the
temptation to add such a control to a menu as it violates GUI design convention.
For our example we will add a separator to our File menu. To do so, simply click on the separator
option in the menu.
As the final entry in the File menu, add an E&xit item.
Página 29
We will now create a second drop down menu. Click in the Type Here field next to the File menu and
enter &Edit to create an Edit menu. Use the same technique outlined above to add Cut, Copy and
Paste items to the Edit menu.
The last task in creating our top-
level menu is to add a Checked
menu item. A checked menu item
maintains state of being either set
or unset. When a Checked item is
set, a check mark appears and
when they are unset the check
mark disappears. Once completed
the form layout should appear as
follows:
To create a Checked item in the
menu enter Save on Exit in the
Type Here field and then right
click on the item to display the
popup menu. From the menu, se-
lect Checked. The menu item will
now be displayed with a check
mark next to it. In the property
panel for the checked menu item,
change the Name property to
SaveOnExitMenu.
The menu is now ready to be
tested. Press the F5 key to build and run the application. When it appears, click on the File and Edit
menus to confirm that they appear as you intended.
Deleting and Moving Menu Items
To delete a menu item in Visual Studio, simply right click on the item and select Delete from the
popup menu. To move an item within the same menu, click and drag the item to the new position by
holding down the mouse button. Release the button when the mouse pointer reaches the new location.
To move an item from one menu to another, first right click over the menu item then select Cut from
the popup menu. Next, click on the new menu to which you wish to move the item and, with the
mouse positioned on the menu item you wish to appear below the new item, right click and select
Paste.
Assigning Keyboard Shortcuts to Menu Items
Página 30
It is conventional to allow menu items to be selected using the keyboard using what are known as
keyboard shortcuts. These are key sequences that typically involve pressing a key whilst holding
down the Ctrl, Alt or Shift key.
Keyboard shortcuts are defined by setting the ShortcutKeys property of a menu item object. For ex-
ample, to configure the Exit menu item to use Ctrl-X, select the menu item and click in the value field
of the ShortcutKeys property in the Visual Studio Properties panel. A panel will appear providing the
option to select Ctrl, Shift or Alt and also the key to be pressed in conjunction. Use this panel to
configure the Ctrl+X key sequence for this menu item.
Programming Menu Items in C#
Now that we have designed a menu system in Visual Studio, the next step is to make the menu items
do something when they are selected by a user. This is achieved using the event procedures of the
individual menu options. We will demonstrate this using our example by wiring up the Exit menu
option so that it closes the application, and by writing an event procedure for the Save on Exit menu
option to change the checked status of the Checked menu item.
We will begin by writing a C# event procedure for when the Exit menu option is selected. In Visual
Studio click on the File menu so that the menu drops down and double click on the Exit menu option.
Visual Studio will subsequently display the Click event procedure for this menu item. All we need to
do is add a Close() call to this procedure to exit the application:
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Close();
}
Having made the appropriate change, press the F5 key to build and run the application. Selecting the
Exit option from the File menu should now cause the application to close. Restart the application and
try the Ctrl+X keyboard shortcut to Exit the application.
The final step is to write some C# code to change the setting of the SaveOnExitMenu object such that
selecting the option in the menu changes the checked status. To achieve this, double click on the Save
On Exit in the Edit menu to display the Click event procedure for this object. Enter the following C#
code to invert the current setting of the Checked property of the SaveOnExitMenu object:
private void SaveOnExitMenuItem_Click(object sender, EventArgs e)
{
SaveOnExitMenuItem.Checked = !SaveOnExitMenuItem.Checked;
}
Press F5 to build and run the application once again. When Save on Exit is clicked, the checked status
will change to either, set or unset depending on the current setting.
Página 31
Creating Context Menus in C#
C# context menus are the menus that pop up when the user clicks with the right hand mouse button
over a control or area in a Windows based form. They are called context menus because the menu is
usually specific to the object over which the mouse was clicked. Context menus are also sometimes
referred to as Popup menus or Shortcut menus.
This chapter will provide an overview of the steps necessary to create and program Context menus in
C#. For information on creating Top-level menus see the Creating Top-Level Menus in C# chapter of
this book.
Adding Context Menus to a C# Form
Context menus are added to a form in C# using the ContextMenuStrip object and associating it with a
particular control. Begin by creating a new Windows Application project in Visual Studio. Next, add
a RichTextBox component to the form so that the form appears as follows and name it MyTextBox:
The purpose of this example is to create a context menu on the form
which will contain options to hide and show the MyTextBox object.
From the Visual Studio Toolbox, double click on the ContextMenuStrip
object. The object will be added to the form. You will notice, however,
that since the menu is not located at any specific position in the form, it
is located in the panel beneath the form. To display the menu in the form,
or edit properties of the object, simply click on this instance of the object.
With the object selected, change the name to TextBoxMenu by changing
the Name property in the Properties panel. You will notice also, that a
representation of the context appears in the form area:
Página 32
Add items to the menu simply by
typing in the Type Here fields.
Each time you enter a new item a
new Type Here field will appear.
To add an item other than a menu
option, click on the small down ar-
row which appears in the text box.
It is possible to add ComboBoxes,
Separators, TextBoxes and Menu-
Items to a context menu. With the
exception of separators and Menu-
Items, these items should not be
placed in menus because they vio-
late the rules of good GUI design.
Once an item has been added to
the menu, right clicking on the
item provides a list of properties
which may be changed, such as
making an item checkable, or dis-
abling an item so that it cannot be
selected by the user. It is also pos-
sible to define an image to be dis-
played for the menu option.
To complete this phase of the tutorial, add menu items labeled Hide and Show.
Associating a Component with a Context Menu
Now that we have designed our context menu we need to associate it with the form object. To do this,
select the form in Visual Studio and scroll through the properties in the Properties panel until you find
the ContextMenuStrip property. Click on the down arrow in the value field and select TextBoxMenu
to associate this menu with the form.
Press F5 to build and run the application. When the application loads, right click with the mouse on
any part of the form to display the context menu.
Programming C# Context Menu Options
Now that we have designed the context menu, and associated it with the form object, we need to write
some C# code to cause the MyTextBox object to hide and show depending on the menu selection. This
is achieved by implementing Click event procedures for the hide and show menu items. In Visual
Studio, select the TextBoxMenu object in the panel beneath the form. Once selected, a representation
of the context menu will appear in the form. Double click on the Hide menu option to display the
Página 33
Click event procedure code for this menu option. We now need to write some C# code to call the
Hide() method of the MyTextBox object as follows:
private void hideToolStripMenuItem_Click(object sender, EventArgs e)
{
MyTextBox.Hide();
}
Similarly, the Click event of the Show menu option can be implemented to call the Show() method of
the MyTextBox object. Double click on the Show item of the context menu in the form to display the
event procedure and add the call to the Show() method as follows:
private void showToolStripMenuItem_Click(object sender, EventArgs e)
{
MyTextBox.Show();
}
Compiling and Running the Application
Compile and run the application by pressing the F5 key. Right click anywhere on the form to invoke
the context menu and select Hide. The TextBox will disappear from the form. Right click again and
select Show to once again display the TextBox:
Building a Toolbar with C# and Visual Studio
Toolbars provide a quick way for users to perform tasks without having to navigate the application's
menu system. For this reason alone, no Windows application would truly be complete without at least
one toolbar. In this chapter of C# Essentials we will cover in detail the topic of creating toolbars in C#
using Visual Studio.
Creating a Toolbar
Página 34
Toolbars are referred to in C# as ToolStrips. The first step in creating a toolbar is to add a ToolStrip
control to the form. Begin by starting Visual Studio and creating a new Windows Application project
named CSharpToolbar. When the new project has been created and the default form appears, display
the Toolbox and double click on the ToolStrip control to add it to the form:
Various types of control can be
added to a toolbar. To add a con-
trol, simply click on the down ar-
row of the button on the toolbar. A
menu will appear listing the vari-
ous types of control which may be
added. Select a button control.
Once the new button control has
been added, right click on the but-
ton to display a menu containing
various options for modifying the
control (including setting a new
image on the button).
Using the above technique add
two more buttons to the toolbar.
Press F5 to build and run the ap-
plication. The application should
appear as follows:
Adding Tooltip Text to Toolbar Controls
Tooltips are small messages which are displayed when the mouse
pointer moves over a control. They are intended to provide a brief
description of the function of the control. Tooltips are especially
useful for toolbar controls because such controls are typically small
buttons which only display a small icon. This means it is often not
clear exactly what a control does. By defining a Tooltip, it is possible
to provide useful tips to the user as to what the control does.
Tooltips are specified via the Text property of the control in question. To add Tooltip to the first button
in our example toolbar, select the button in the form and change the Text property in the Properties
panel to Displays Date and Time. Similarly change the Text property of the second control to Hides
Date and Time.
Press F5 to build and run the application. When the application starts, move the mouse over each
button. As the mouse hovers over each control the tooltip text should appear.
Página 35
Programming Toolbar Controls
In order to make the toolbar controls useful we need to write some C# code in the event procedures.
For the purposes of this example, we will program two of our toolbar controls to hide and show a
DateTimePicker control. Open the Toolbox if it is not already visible and double click on the
DateTimePicker control to add it to the form. Move the new control so that it appears as follows:
With the DateTimePicker control
selected, change the Name prop-
erty in the Properties panel to My-
DateTime.
Finally, we need to write the C#
code to hide and show the date and
time control. Double click on the
first button in the toolbar to dis-
play the Click event procedure for
this control. The event procedure
needs to call the Show() method of
the MyDateTime object as fol-
lows:
private void toolStripButton1_Click(object sender, EventArgs e)
{
MyDateTime.Show();
}
Similarly, we need to call the Hide() method of the MyDateTime object when the second button is
pressed as follows:
private void toolStripButton2_Click(object sender, EventArgs e)
{
MyDateTime.Hide();
}
Once the C# code has been written, press F5 to build and run the application. When the toolbar buttons
are clicked the date and time control will appear and disappear accordingly.
Changing the Toolbar Position
Página 36
By default, the ToolStrip object will be position across the top edge of the form. Whilst this is the
most common location for a toolbar, it can be positioned along the top, bottom, left or right edges of
a form, or even in the center of the form using the Dock property. To modify this property, select the
ToolStrip object in the form and look for the Dock property in the Properties panel. Click on the down
arrow in the value field to display the location map:
Click on the new location and the toolbar will move to the new position.
Using Bitmaps for Persistent Graphics in C#
In the previous chapter we looked at the basics of drawing graphics in C# using the Graphics Object.
In that chapter we dealt with the issue of making graphics persistent by performing all the drawing
sequences in the Paint() method of a component. In this chapter we will look at using bitmaps to
provide persistent graphics
Why Use Bitmaps for Graphics Persistence in C#?
In the previous chapter we explained that simply drawing graphics on a component in C# is not suffi-
cient to ensure the graphics will remain if part or all of the window containing the graphics is obscured
by another window. In such situations the application will not know to redraw the erased graphics
once the obscured section of the window is uncovered. To address this problem we used the Paint()
method of the component to ensure that the draw commands were executed again when the Paint()
event was triggered. This approach works well for simple, pre-defined graphics but is not suitable for
complex drawings or situations where different graphics are drawn each time the application runs (for
example the graphics may be drawn based on interaction with the user).
To address such situations it is preferable to draw the graphics on a bitmap residing in memory which
can be rendered on a component whenever the a Paint() event is triggered. This avoids the problem of
Página 37
having to call all the Draw methods or store and replay a complex sequence of draw commands each
time the graphics need to be refreshed.
Creating a Bitmap
The first step in this tutorial is to create a new Visual Studio Windows Form Application project
named CSharpBitmap. Once the project is created, double click on the Form to display the source
code. Within the class declaration for the form we need to add a Bitmap declaration called myBitmap
as follows:
namespace CSharpBitmap
{
public partial class Form1 : Form
{
private System.Drawing.Bitmap myBitmap; // Our Bitmap declaration
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
This bitmap will be used to store the graphics image in memory ready to be displayed to the user.
Instantiating a Bitmap and Creating a Graphics Object
Having declared a Bitmap to store our graphics we now need to instantiate it. This can be performed
in the Form1_Load() method of our form so that it is executed when the form is created:
private void Form1_Load(object sender, EventArgs e)
{
myBitmap = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
}
Having created a bitmap object the next step is create a Graphics Object for the bitmap so that we can
draw graphics into the bitmap. This is achieved by calling the Graphics.FromImage() method, passing
through the bitmap as the argument. Our Form1_Load() method should now appear as follows:
Página 38
private void Form1_Load(object sender, EventArgs e)
{
Graphics graphicsObj;
myBitmap = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
graphicsObj = Graphics.FromImage(myBitmap);
graphicsObj.Dispose();
}
Note that it is important to dispose of the Graphics Object before we exit the method to free up
resources.
Drawing onto the Bitmap
Now that we have our object we can draw onto it using the Graphics Object just as we would writing
to any other graphics object (for details on drawing to a graphics object read Drawing Graphics in
C#).
In this example we will create Pen and Rectangle objects and use them to draw an ellipse:
private void Form1_Load(object sender, EventArgs e)
{
Graphics graphicsObj;
myBitmap = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
graphicsObj = Graphics.FromImage(myBitmap);
Pen myPen = new Pen(System.Drawing.Color.Plum, 3);
Rectangle rectangleObj = new Rectangle(10, 10, 200, 200);
graphicsObj.DrawEllipse(myPen, rectangleObj);
graphicsObj.Dispose();
}
When compiled and executed the code will create the bitmap in memory, create a Graphics Object
associated with the bitmap and draw an ellipse into the bitmap image. It will not, at this point, display
anything to user because the bitmap is still just an image sitting in memory. The next task is to wire
up the Paint() event to render the bitmap into the Graphics Object of our form.
Rendering a Bitmap Image on a Control
Página 39
The next step is to write some code for the Paint() event of our form. Select the form in the Visual
Studio design area and click on the lightning bolt button in the Properties dialog to display events.
Double click on the Paint event to go to the code area. In the Paint() event enter the following code to
draw the bitmap image onto the form:
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics graphicsObj = e.Graphics;
graphicsObj.DrawImage(myBitmap, 0, 0, myBitmap.Width, myBitmap.Height);
graphicsObj.Dispose();
}
When compiled and executed the graphics created in the bitmap image will appear in the form area:
Changing the Background Color of a Bitmap
If you followed the tutorial you will now have a plum color circle drawn on a black background. The
background is black because this is the default for a new Bitmap object and we made no attempt
change the color after we created the Graphics Object. Had we wanted a different background color
we could have called the Clear() method of the bitmap's Graphics Object in the Form1_Load()
method, passing in a new color:
private void Form1_Load(object sender, EventArgs e)
{
Graphics graphicsObj;
myBitmap = new Bitmap(this.ClientRectangle.Width,
this.ClientRectangle.Height,
System.Drawing.Imaging.PixelFormat.Format24bppRgb);
graphicsObj = Graphics.FromImage(myBitmap);
graphicsObj.Clear(Color.White); // Set Bitmap background to white
Página 40
Pen myPen = new Pen(System.Drawing.Color.Plum, 3);
Rectangle rectangleObj = new Rectangle(10, 10, 200, 200);
graphicsObj.DrawEllipse(myPen, rectangleObj);
graphicsObj.Dispose();
}
The above code will clear the bitmap prior to creation of the image and, in doing so change the color
of the background to white:
Summary
A more efficient and persistent approach to displaying images in C# can be achieved by rendering
images into memory in the form of a bitmap, and then displaying the bitmap in a component’s Paint()
method. This avoids the necessity to repeatedly perform potentially complex and CPU intensive draw-
ing operations each time an image needs to be rendered or refreshed. In this chapter we have worked
through the steps involved in creating persistent graphics in C# through the implementation of bit-
maps.