Starting Windows - Forms
Starting Windows - Forms
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.
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.
In this exercise you will learn how to use labels, textboxes and the timer.
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.
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:
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?
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";
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();
}
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:
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.
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 Form1()
{
InitializeComponent();
}
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);
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:
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:
……
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.
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:
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