0% found this document useful (0 votes)
26 views15 pages

Starting Windows - Forms

fgfghj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views15 pages

Starting Windows - Forms

fgfghj
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Starting with Windows Forms

1 Motivation and learning objectives


The applications that we have been building up to now do not have an
especially nice user interface. The program writes text lines on the screen, and
the user answers with text lines written in the keyboard.
To build more attractive and user-friendly applications we will learn to use
Windows Forms that allow us to use windows, buttons, colors, etc. We will see
that using a relatively small set of elements we can build applications with a
really impressive appearance.
In particular, in this activity you will learn to build simple applications that use
the following elements of Windows Forms:
- Form
- Label
- TextBox
- CheckBox
- RichTextBox
- Button
- RadioButton
- Timer
- DataGridView
- Menu of options
- Panel
- Picture Box
- Drawing lines and polygons
- OpenDialog and SaveDialog

2 A Simple Windows Forms Application


Start Microsoft Visual C# 2010 Express Edition and create a new project.
But now, select a Windows Forms application (not a Console Application, as we
have been doing up to now). You will see something like Figure 1.

2. 1
Figure 1 Windows Form Application
Now, in the area where you had the C# code in your Console
Applications, we have an empty form (a window) called Form1. And you can
see also (in the bottom-right corner) a window that shows the properties of the
form. There are a lot of properties, and you can change the values of these
properties directly. For example, change now the Text property that contains the
text that is shown in the top-left corner of the form. Write for instance “My first
form”. You can also change the background colour of the form, changing the
value of the BackColor property.
On the left hand side of the screen, you can identify a vertical bar with
the name “Toolbox.” If you click on this bar, you will see something like Figure
2.

Figure 2 Toolbox

2. 2
This is a long list of elements that can be included in your form. Look for an
element of type button and move it on your form. Now your application has
already two elements: the initial form and a button on it (see Figure 3).

Figure 3
In the properties window, you can see the properties of the button, for example, the type of Font
for the text that appears on the button. Change this text (in the Text property) so that you can
see the text “Mi botón” in the button.
The key question now is that we have to write the code that must be executed in response to
certain events that may happen to the elements of your application (forms, button, etc.). For
instance, if the user clicks the button we want to write a message on the screen. This will be our
first project.
In the window of properties of the button, there is an icon with a lightning (Figure 4). If you click
this icon, you can see a long list of events associated with buttons.

Figure 4
One of these events is the Click event. Select (double click on) this event. The system will show
a window to write code (figure 5).

2. 3
Figure 5 Button Click Event Code
The void function button1_click will be executed when the user clicks the button. And we want to
write a message on the screen. To do that, write the following code in the body of the function:
MessageBox.Show("My first project works");
This is all the code we need to write in our project (in fact, as we will see later, our project has
some more code that has been automatically included, but we do not have to touch this code).
Just above the window showing the code you can identify three buttons with the names:
Form1.cs*, Form1.cs*(Diseño) and Página de Inicio. If you select the first one you will see the
code of the form and if you select de second one you will see the form with its elements
(buttons, boxes, colours, etc.).
We are ready to run our program. Click on the green triangle as usual to run Microsoft Visual C#
programs and see what happens. The program presents you the form with the button. If you
click on the button then your message will appear.
Now stop the program and include the following sentence in the code of function button1_click:
MessageBox.Show("My first project works");
this.BackColor = Color.Green;
Your program, after showing the message will change the background colour of the form.

3 The key idea: event-driven programming


Windows Forms applications use the event-driven model of programming. That is, the
application contains objects (for example forms and buttons), and you have to write the code
that must be executed in response to certain events that may happen to these elements.
You have seen a simple example in which the only event treated was the click of the button. But
every element contained in your program has a lot of possible interesting events. For example,
the form that you have in your project also has some events associated with. One of the most
important events associated with a form is the Load event, that allows you to execute some
code just when the form is loaded (that is, presented to the user).
Select the Load event of your form and include in the associated function (that will be named as
Form1_Load) the code to show a welcome message when the program starts. Run the program
and check that everything is ok.
You can execute your program step by step, as we do with Console Applications. Use F11 to
advance step by step. You will notice that the first code you see when executing the application
step by step is code that you have not written. This is the code that we mentioned before that

2. 4
has been automatically included in your application. You can ignore this code but it is important
that you do not change it. Advance execution with the F11 key. The first code that you will
recognize is the code of function Form1_Load that is executed as a result of presenting the form
to the user (your treatment for the Load event). Continue advancing with F11 and you will see
your form in the screen. If you click the button you will see your code to treat the click event.
Finally, do not forget to save your project from time to time.

4 A few more elements for our Windows Forms programs

In this exercise you will learn how to use labels, textboxes and the timer.

4.1 Labels and Textboxes


Let’s start a new project that will allow us to write a number and will write the double of this
number. Nothing spectacular but it is just an excuse to use a few new elements.
The form for this project must look like figure 6.

Figure 6 Button Compute, labels and textboxes


Our form uses a button (compute) and two types of new elements: label and Textbox. Both
types of elements have been selected from the list of elements that can be found in the Toolbox.
A label just allows us to put text in the form. We have used two labels to identify where in the
form the user must introduce the number and where the application will show the result. The
text to be shows must be written in the Text property of the label. In this case, we also changed
the BorderStyle property of the label.
The second element that has been used is a TextBox that allows us to introduce text in the
application and also can be used to write text for the user. In this case, we have used a TextBox
so that the user can write the number. This TextBox is named entrada (you can see in the
window of properties that we have changed the name property). We have used a second
TextBox named salida. The program will show the result in this box.

2. 5
Again, the only event in our program will be the response to the click on the button. The user
must write a number in the left TextBox and click the button. The program will show on the right
TextBox the result (the double of the input). The code of function button1_click is:
private void button1_Click(object sender, EventArgs e)
{
int res;
res = Convert.ToInt32(entrada.Text)*2;
salida.Text = Convert.ToString(res);
}
When the user clicks the button, we take the text form the input TextBox (named entrada),
convert it to an integer and compute the result (the double of the input). Then we convert this
result to a string to be shown in the output TextBox (named salida). Execute the code and check
that it works.
Since our Windows Forms programs must be robust, we must check in the code for the
possibility that the user does not introduce a number (a format error). We already know how to
do that. Look at this new version of the code to treat the click event:
private void button1_Click(object sender, EventArgs e)
{
int res;
try
{
res = Convert.ToInt32(entrada.Text) * 2;
}
catch (FormatException)
{
MessageBox.Show ("Format error");
salida.Text ="Error";
return;
};

salida.Text = Convert.ToString(res);
}
Include that code in your application and check that it works.

4.2 The Timer


Next, we will introduce a new element called timer. The timer allows us to set a time interval,
and it launches a tick event after this interval continually. Thus, we can count time by just
counting the number of tick events.
In particular, we want that our program shows the count of seconds in the top-right corner. To
that purpose, we need two labels. One will have the text Seconds and the other one will show
the count of seconds (we could also use a TextBox for both purposes, but labels are better
when you only want to show information to the user). And we need also to include a timer,
which you can find in the list of elements (toolbox). After including these elements, your screen
should look something like figure 7.

2. 6
Figure 7 An example of the use of the timer
The timer must be initialized when the application starts execution. The best way to do that is to
include the initialization code as a treatment for the Load event of the form, that, as you know, is
the first thing that will happen when executing our program. Look at this code:

private void Form1_Load(object sender, EventArgs e)


{
timer1.Interval = 1000; // Set time interval to 1 second
timer1.Start(); // Start launching tick events
// every 1 second
}
When the main form is shown to the user the Form1_Load function will be executed. This
function indicates to the timer that it should launch a tick event every second (1000
milliseconds). It also starts the timer with the method Start().
Now we have to write the code to treat the tick event of the timer, that will occurs every second.
The code is that:

// This code is automatically executed for each tick event


private void timer1_Tick(object sender, EventArgs e)
{
int segundos;
segundos = Convert.ToInt32(label4.Text)+1;
label4.Text = Convert.ToString(segundos);
}
The function that is executed as a result of the tick event just takes the contents of label4, adds
one and puts the new value back to the label. Obviously, label4 is the label that contains the
count of second. In this case, we did not change the name of the label (label4 is the name that
the system gave automatically to that label). Write this code in your application and check that
everything is OK.
Try the following changes to the code yourself:
 Can you make the required changes to the code so that when the timer reaches 10
seconds the button changes color?

2. 7
 Can you make the required changes to the code so that when the timer reaches 15
seconds change the position of the button in the form?

5 Using a grid of cells


Another element that may be very useful in our projects is a grid of cells that allow us to show a
collection of data (for example, a list of clients). Start a new project and include in the main form
a DataGridView element (from Toolbox). Give a proper name to that grid (for example, matriz).
We will use this element to show a matrix of ten by ten cells. When we click on one cell, the
application should change the colour of this cell.
Again, the load event for the main form is the ideal place to fix some initial properties of the grid.
Look at this code:
private void Form1_Load(object sender, EventArgs e)
{
matriz.ColumnCount = 10;
matriz.RowCount = 10;
matriz.ColumnHeadersVisible = false;
matriz.RowHeadersVisible = false;
matriz.AutoSizeColumnsMode=DataGridViewAutoSizeColumnsMode.
AllCells;
}
When starting the program (that is, when loading the main form) we fix the number of rows and
columns, and eliminate the row and columns headers which are not useful in this exercise.
Finally, we indicate that columns size must be adjusted automatically to the size of the contents
of the cell.
If you run the program, you will get something like figure 8.

Figure 8
That is, the grid is not large enough for the 10x10 cells and there are two scroll bars that, in this
case, we do not like (in other application these scroll bars may be usefull).
You can solve the first problem by clicking on the grid and dragging the borders until the grid
has the desired size. To eliminate the scroll bars you can change the ScrollBars property
directly in the window of properties. You must assign the value None to that property.

2. 8
Now we have to write the code to treat the event that is launched when the user click on one of
de cells of the grid. This code should change the colour of the cell that has been selected. The
code es following:
private void matriz_CellClick(object sender,
DataGridViewCellEventArgs e)
{
int i, j;
i = e.RowIndex;
j = e.ColumnIndex;
matriz.Rows[i].Cells[j].Style.BackColor = Color.Green;
}
Be careful to select the right event. In that case, the CellContentClick event does not work
because the cells are empty. The correct one is the CellClick event. Note that the row and
column that identifies the cell that has been selected are obtained from a special object named
e that is received by the function as a parameter. Include that code in your project and see what
happens. When you click on a cell the colour of that cell must change.
However, you will notice that the selected cell does not change immediately to green. In fact,
the selected cell remains blue until we select a new cell, and at this moment it becomes green.
The problem is that in a DataGridView the selected cell has a default colour (blue in this case).
This is the reason why in figure 8 we can see that cell 0,0 is blue, since this cell is the selected
one by default when the program starts. The problem can be solved very easily including the
next sentence at the end of matriz_CellClick:
matriz.ClearSelection();
This operation makes the selected cell to become unselected, so it is not blue any more but
gets the colour that has been assigned to the cell (in this case, green).
Sometimes you need to write names or numbers inside the cells of the DataGridView. This is
the code to write number 7 in the selected cell, and the word “OK” in the next cell in the same
row:
matriz.Rows[i].Cells[j].Value = 17;
matriz.Rows[i].Cells[j+1].Value = "OK";

6 Working with multiple forms


Next, let´s add more code so that when the user clicks on a cell a new form is presented where
the user can select the colour for the cell that has been clicked.
To include a new form you have to select option Proyecto->Agregar Windows Form in the top
toolbar. A new form that will be named Form2 is presented, where you can include the elements
you want for your application. In our case, we want this form to appear when the user clicks one
cell. And we want that the form shows the row and column of the cell that has been selected
and a button that allow us to choose a new color for that cell. We include first the required labels
and button (figure 9).

2. 9
Figure 9
We have used two labels to show the row and column of the selected cell. These labels have
been named r and c. In both of them we set the BorderStyle property to FixedSingle and the
autosize property to false so that the size of the label does not change automatically.
Now, let’s look at the code for Form2:
public partial class Form2 : Form
{
int fila;
int columna;
Color nuevocolor;

public Form2()
{
InitializeComponent();
}

public void pon_fila(int f)


{
fila = f;
}

public void pon_columna(int c)


{
columna = c;
}

public Color dame_nuevocolor()


{
return nuevocolor;
}

private void Form2_Load(object sender, EventArgs e)


{
// The values of fila and columna have been set in Form1
r.Text = Convert.ToString(fila);
c.Text = Convert.ToString(columna);
}

private void button1_Click(object sender, EventArgs e)


{
ColorDialog selcol = new ColorDialog();

2. 10
selcol.ShowDialog();
nuevocolor = selcol.Color;
Close();
}
}
Pay special attention to the way of passing information from one form to the other. First, notice
that we have declared three variables in the second form: fila, columna and nuevocolor, one for
each data we want to share between the two forms. We have also defined three functions so
that Form1 can access them: pon_fila and pon_columna to allow Form1 writing fila and
columna, and dame_nuevocolor to allow Form1 reading nuevocolor.
In particular, before activating the Form2, the main form Form1 will write in fila and columna the
row and column that identify the selected cell. To that purpose, Form1 uses the functions
pon_fila and pon_columna, that belong to Form2 (you will see that very soon). When Form2 is
loaded (that is when function Form2_Load is executed) the row and column numbers that can
be found in variables fila and columna are shown in the corresponding labels. If the user clicks
the button, then the button1_Click function uses an object of type ColorDialog to present to the
user a menu to select a colour. The selected colour is assigned to the variable nuevocolor, so
that Form1 can read it, using function dame_nuevocolor.
Let’s look at the code for Form1:

private void matriz_CellClick(object sender,


DataGridViewCellEventArgs e)
{
int i, j;
i = e.RowIndex;
j = e.ColumnIndex;

Form2 F2 = new Form2(); // Create a new Form2


F2.pon_fila(i); // Set the value of fila in Form2
F2.pon_columna(j); // Set the value of columna in Form2
F2.ShowDialog(); // Show Form2 (Form2_Load executes now)

matriz.Rows[i].Cells[j].Style.BackColor =
F2.dame_nuevocolor(); // Get nuevocolor from Form2
matriz.ClearSelection();
}
When the user clicks on a cell, the matriz_CellClick function creates a new form F2 of the type
Form2 and writes the row and column indexes of the selected cell in the variables fila and
columna of F2 using the pon_fila and pon_columna functions. Then, it activates F2 using the
sentence F2.ShowDialog(). This is essentially like calling a function that makes F2 appears in
the screen, and it is at this moment that the Form2_Load method is executed. Then, the user
will click the button to select a new color. When all this finish, F2 will desapear and we will return
to the matriz_CellClick function, that takes the selected colour from the variable nuevocolor of
F2 using the dame_nuevocolor function.
Include this code in your project and check that it works properly. Try to include the code
required to assign the selected color not only to the selected cell but also to all the cells in the
same row and in the same column.

6 Menus for our applications


It may be very useful to include in our applications the typical menu with a list of options, as
many windows applications do. To that purpose you have to include a menuStrip element from
cuadro de herramientas. As shown in figure 10, you can very easily configure a menu of options
in a hierarchy. In our case we want two options: to change the color of the main form and to
write a goodby message to the user.

2. 11
Figure 10
With a double click in one of the options the system presents to you a function that will be
executed if that option is selected. We have to write here the code we want to execute once the
option is selected. In the case of the option to change the color of the main form, the code could
be:
private void changeColorToolStripMenuItem_Click(object sender,
EventArgs e)
{
ColorDialog nuevocolor = new ColorDialog();
nuevocolor.ShowDialog();
this.BackColor = nuevocolor.Color;
}

7 Graphics
In some applications it ca be useful to use graphics (images, lines, poligons, etc.). Let’s learn
the basics about graphics. To that purpose, we will build a simple application that:
 When clicking a button shows the image of an aircraft
 When the Form is loaded shows a rectangle
 When the user clicks on the form with the mouse the aircraft moves to the clicked
position, ploting a red line from the original point to the new one
 If the new position is inside the rectangle, fills the rectangle with red colour.

Start now a new Windows Form project and add a Panel (you will find this control in the group of
containers in the toolbox) and a button. The Panel control provides a simple frame for putting
subcontrols inside. Write the following code to the click event of the button:

public partial class Form1 : Form


{
PictureBox aircraft = new PictureBox();

public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)

2. 12
{
aircraft.Width = 20;
aircraft.Height = 20;
aircraft.ClientSize = new Size(20, 20);
//point where the image will be shown
aircraft.Location = new Point(20, 50);

// Adjust the image size to 20x20


aircraft.SizeMode = PictureBoxSizeMode.StretchImage;

//the file should be in the debug folder


Bitmap image = new Bitmap("avion.gif");
aircraft.Image = (Image)image;
panel1.Controls.Add(aircraft);
}
}

This image of the aircraft is in file "avion.gif" that must be found in the Debug folder of the
project (you will find easily in internet gif files with aircraft images). To handle this image we
need an object of class PictureBox (named aircraft), that has been declared as global to the
project.

When clicking the button we adjust a few parameters of the PictureBox (for instance, the XY
position where the image must be shown), load the PictureBox with the image from the gif file,
and put the PictureBox in the panel (the name of the panel is panel1, which is the name given
automatically by the system when we created the panel). As a result, the image of the aircraft
will be shown in the form. Try this code and check that it works well.

The second step is to draw a rectangle inside of panel.The panel has an event callet Paint. The
Paint event is raised every time the computer must redraw the graphips in our application (for
instance, just after the Load event, or when the user minimizes and then maximizes the form).
Therefore, the code to treat the Paint event is the right place to include the code to draw graphic
elements in the panel. Include the following code in the treatment of the paint event of the panel:

private void panel1_Paint(object sender, PaintEventArgs e)


{
System.Drawing.Graphics graphics = e.Graphics;

// Colour to draw the rectangle


Pen myPen = new Pen(Color.Red);

// Points that define the rectangle


Point[] polygonPoints = new Point[4];
polygonPoints[0] = new Point(100,100);
polygonPoints[1] = new Point(100,150);
polygonPoints[2] = new Point(150,150);
polygonPoints[3] = new Point(150,100);

//Draw the rectangle


graphics.DrawPolygon(myPen, polygonPoints);
myPen.Dispose();
}

As you can see, the code declares a vector of points called polygonPoints to represent a
rectangle (we need four points). We assign a point to every position of this vector. Every point is
built from two coordinates, and the four points define a rectangle. The, we tell the system to
draw the rectangle in the panel, using the red colour to paint the lines of the rectangle.

2. 13
Try this code and check that it works well. When the form is loaded you will see the red rectable
and when you click the button you will see the aircraft. If you do not see the rectangle probably
the reason is that your panel is too small. Make it bigger by dragging the borders of the panel.

Next, we add the code to treat a new event: the user click the left button of the mouse to
indicate the point where the aircraft must be moved. But first we need a Point that will be used
to store the position of the aircraft before moving it. We will need this point later to draw a line
from the previous position of the aircraft to the new one. Look at the code bellow:

public partial class Form1 : Form


{
PictureBox aircraft = new PictureBox();
Point lastPosition; //To save position before moving aircraft

……

private void panel1_MouseClick(object sender, MouseEventArgs e)


{
//Save the current location of aircraft
lastPosition = aircraft.Location;

// obtain the point that has been clicked


// we have to move the aircraft to this point
aircraft.Location = new Point(e.X, e.Y);

// we force the control to be redrawn and


// the line is updated
panel1.Invalidate();
}

Notice that we declare the Point called lastPosition as a global object, as the PictureBox,
because it will be used in several functions. In the treatment of the click event we save first in
lastPosition the current position of the aircraft (that we get from the PictureBox). Then we
get the point that was clicket by the user (we already know how to get this point), and assign
this point as the new position for the aircraft. Finally, invalidate the panel to force the redrawn,
so that we will see the aircraft in the new position. Try this code and check that it works.

Next, we add the code in Paint event to draw a line from the last position to the new one. We
also will include the code required to check if the new position of the aircraft is inside the
rectangle. If it is inside we must fill the rectangle in red colour. Look at the new version of code
in pane1_Paint.

System.Drawing.Graphics graphics = e.Graphics;

// Points that define the rectangle


Point[] polygonPoints = new Point[4];
polygonPoints[0] = new Point(100, 100);
polygonPoints[1] = new Point(100, 150);
polygonPoints[2] = new Point(150, 150);
polygonPoints[3] = new Point(150, 100);

//Draw the line


Pen myPen = new Pen(Color.Red);
graphics.DrawLine(myPen, lastPosition, aircraft.Location);

// Draw the rectangle.


// if "aircraft" is inside
if ((aircraft.Location.X > 100) &&
(aircraft.Location.X < 150) &&
(aircraft.Location.Y > 100) &&

2. 14
(aircraft.Location.Y < 150))
{
//Fill the polygon with red colour
SolidBrush myBrush = new SolidBrush(Color.Red);
graphics.FillPolygon(myBrush, polygonPoints);
myBrush.Dispose();
}
else
// Draw an empty polygon

graphics.DrawPolygon(myPen, polygonPoints);

myPen.Dispose();

The code simply checks if the point is inside the rectangle. If so, it draws a rectangle filled with
red colour. If not it draws an empty rectangle. The code also draws a line from the last position
to the new one.

Finally, you may want to do something when clicling on the aircraft (for instance, showing this
message “This is my aircraft”). To that purpose, insert the following code at the end of
button1_Click:
aircraft.Tag = "Juan";
aircraft.Click += new System.EventHandler(this.evento);

So, when creating the pincture box we assign it a Tag (for instance, the name of the owner of
the aircraft) and assign a handler to the Click event. As a result, when clicking on the aircraft
image the function named evento will be executed. The code for this handler is:

private void evento(object sender, EventArgs e)


{
PictureBox p = (PictureBox)sender;
string nombre= (string)p.Tag;
MessageBox.Show("This is my aircraft and I am:" + nombre);
}

First, we get the object that sent the event (the picture box). Then we get the tag to identify the
object and write the message. Notice that we may have different picture boxes (different
aircraft). Each of them will have a different tag to identify it. But all of them could have the same
handler for the click event. The code for this handler will identify (using the tag) the object that
generated the event.

2. 15

You might also like