Welcome to Wynthar's C# Tutorial Series Tutorial 3: Form Properties And Making A Timer Introduction
So in the
Last Tutorial we learned a little bit more about windows forms. We created a form label, text box, and check box. Then, we coded the buttons to change the form's title and modify the text of a label.
This time
I am going to assume you have been following the tutorials up to this point, or have enough knowledge to create a form with the windows forms objects that I have on our form to start.
Properties Explanation
Each object on the windows form, including the form itself, has some properties that can bet set, changed and modified. Below is an image of all the properties available for a windows forms button. If you select a particular property a short description of that property will show up at the bottom of the toolbar. In this example, the Text property is selected. As you can see, the description is "
Text The text associated with the control." Try clicking on several different properties and read what the descriptions are. Then, try clicking on various forms objects. You will notice that different objects have different sets of properties.
Let's Begin
I started a new project called Tutorial 3 and added a few objects to the form.
Next
Let's start modifying some of the properties. So, click on the first button. Then, change the
Text property to "Start"
Next
Change the
(Name) to "buttonStart" without the quotes of course.
Next
Excellent. Now let's change the second button. Set the
(Name) to "buttonStop" and
Text to "Stop"
Next
Now, let's set label1's properties. Change
Text to "Wynthar's Awesome Timer" or something to your liking. Expand the
[+] Font property. If you double-click the
Bold property, it should change from False to True. Then, below that, change
ForeColor to something more lively.
Next
Let's modify the check box. Change
(Name) to "checkBoxSuperSize" and change
Text to "Super Size"
Next
Finally, choose the second label. Find the property
AutoSize double click it to change it to False. Then you will be presented with some small white boxes around the label that you can use to resize the label. Resize it to a rather large area as I have done in the screen shot.
Next
Change the
TextAlign property to MiddleCenter by clicking on the middle box when you press the drop down arrow for the property.
Next
Excellent. Now we are ready to start adding the code. So, now double-click on the title bar of the Form1. You can double-click right on the word "Form1" in the title bar. It will automatically take you to the code page and generate a method stub. Enter the following code.
Code:
private void Form1_Load(object sender, EventArgs e)
{
label2.Text = "00:00";
}
Code Explaination
Basically, this just sets the second label's text to 00:00 when the form loads. Pretty self explanatory. Now, a tricky tidbit. Go up to the code public Form1() { InitilizeComponent(); } This is called the "Constructor" because it is a function that has the same name as the class name. (The class name is Form1, as well as this Constructor is named Form1)
In the constructor let's add the following bit of code.
Code:
public Form1()
{
InitializeComponent();
timer1 = new Timer();
timer1.Interval = 1000;
}
Code Explaination
If you type this in, you will notice a red squiggly line appear under timer1. This is because we have not declared a variable yet called timer1. So, we want this timer variable to be available to all methods for this class. So, we are going to create the Timer variable outside of any of the functions so far. So, right below the closing brace } for the constructor, add a line Timer timer1; While we're here, add int seconds = 0; as well.
Code:
public Form1()
{
InitializeComponent();
timer1 = new Timer();
timer1.Interval = 1000;
}
Timer timer1;
int seconds = 0;
private void Form1_Load(object sender, EventArgs e)
{
label2.Text = "00:00";
}
Code Explaination
Once you enter this variable, you will notice the red squiggly line under the timer1 in our constructor goes away. This is because there is no longer an error since we have declared our variable, timer1.
So, let's go back into the constructor and add a new line after timer1 = new Timer(); This line is going to be tricky, so I'll add screen shots.
Start typing the following code... timer1.Tick += Be sure to TYPE at least the += part, do not copy and paste the +=. If you type it, you will see the following screen shot.
Next
So, when you type the += part of timer1.Tick += you will see it says
new EventHandler(timer1_Tick); (Press TAB to insert) how nice! So press TAB!
Next
Again! It says
Press TAB to generate handler 'timer1_Tick' in this class so press TAB again! Now you have a new function timer1_Tick. Let's add some code for this timer1_Tick function.
Delete the line that reads
throw new NotImplementedException(); Code:
void timer1_Tick(object sender, EventArgs e)
{
seconds++;
string sMinutes = (seconds / 60).ToString();
if (sMinutes.Length < 2) sMinutes = "0" + sMinutes;
string sSeconds = (seconds % 60).ToString();
if (sSeconds.Length < 2) sSeconds = "0" + sSeconds;
label2.Text = sMinutes + ":" + sSeconds;
}
Code Explaination
Okay, well this might look tricky, but it's really simple! The first line simply increments our integer variable "seconds" by 1. So, the first timer "tick" will increment seconds from the value of 0 to the value of 1.
The next two lines create a string called "sMinutes" and sets this string to the value of our seconds divided by 60. In C# (and most computer languages) integers can not be decimals. So, if we take 3 seconds and divide it by 60, we can't have 0.05 since it's a decimal, so the computer rounds down to 0. This is true all the way up till we hit the value of 60. Then 60/60 equals 1. So, at 60 seconds we have one minute! Perfect. The line following that line simply checks to see how long the minutes string is. If it's not two characters, then it pads the string with an extra 0. This will create the 01, 02, 03 effect we desire in a timer.
The following two lines create a string called "sSeconds" and set it to seconds % 60. The % function means "remainder" so the result is whatever the remainder would be after a divison process. For example 3 / 60 would be 0 remainder 3. So we are left with 3. Same with 63 / 60. The answer would be 1 remainder 3, so we again get a result of 3. This way we can find out how many seconds we have after the minutes.
The last line simply combines our minutes with a colon and the seconds. "00" + ":" + "00" results in "00:00"
WOW!
Have you followed along so far? It has taken quite some time to compose this tutorial. Even so, I feel that I am blowing past a lot of side explanations I could be making. Please post in the comments section if you'd like to see more detail, or anything in particular explained.
Next
Let's go back to the form, and double click the Start button. Then add the following code.
Code:
private void buttonStart_Click(object sender, EventArgs e)
{
seconds = 0;
try
{
seconds = int.Parse(textBox1.Text);
}
catch (Exception ex)
{
MessageBox.Show("Could not parse the number in the text box." +
Environment.NewLine + ex.ToString());
}
timer1.Start();
}
Code Explaination
The first line sets the seconds back to 0 in case we have changed it for some reason.
The
try and
catch keywords are special. Basically, it means
try to run the code between the braces, and if it fails for some reason, we
catch the exception so it doesn't crash the program, and we display an error message.
Inside the try section, we have a line
seconds = int.Parse(textBox1.Text); by now you should know that textBox1.Text is the text found in textBox1.
int.Parse(); will attempt to parse the variable to an integer value.
So basically, this code will try to parse textBox1 to see if there is an integer. Then, if there is, we set seconds equal to that parsed integer.
Next
Now, let's go enter some more code. Go back to the form, and double click the Stop button. Let's put this logic in the stop button
Code:
private void buttonStop_Click(object sender, EventArgs e)
{
timer1.Stop();
textBox2.Text = seconds.ToString() + " seconds passed!";
}
Code Explaination
First, we stop the timer.
Then setting the textBox2 text to say "X seconds passed!"
There will be a noticable difference after 60 seconds because this text box will say something like 80 seconds passed, where the display label will say 01:20 because the label breaks the time down into minutes and seconds.
Next
OK! Almost there! Let's do one last block of code! Go back to the form, and double click on the checkbox "Super Size." Then, insert the following code.
Code:
private void checkBoxSuperSize_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxSuperSize.Checked == true)
{
label2.Font =
new Font(label2.Font.FontFamily, 40.0F, FontStyle.Bold);
}
else
{
label2.Font =
new Font(label2.Font.FontFamily, 8.25F, FontStyle.Regular);
}
}
Code Explaination
So, the first line is an if statement. It checks to see if checkBoxSuperSize.Checked is set to true. So, when the user checks this box, this function will get called and if they have just checked it. Then the
if block of code will run. Otherwise, if the user just unchecked the checkbox, the
else block of code will run.
The next statement sets the font of the label to a different font. The else block of code has a statement that changes the font of the label back to our original font.
So, if you have followed along up till now your code should look something like this...
Code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Tutorial3
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
timer1 = new Timer();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
}
void timer1_Tick(object sender, EventArgs e)
{
seconds++;
string sMinutes = (seconds / 60).ToString();
if (sMinutes.Length < 2) sMinutes = "0" + sMinutes;
string sSeconds = (seconds % 60).ToString();
if (sSeconds.Length < 2) sSeconds = "0" + sSeconds;
label2.Text = sMinutes + ":" + sSeconds;
}
Timer timer1;
int seconds = 0;
private void Form1_Load(object sender, EventArgs e)
{
label2.Text = "00:00";
}
private void buttonStart_Click(object sender, EventArgs e)
{
seconds = 0;
try
{
seconds = int.Parse(textBox1.Text);
}
catch (Exception ex)
{
MessageBox.Show("Could not parse the number in the text box." +
Environment.NewLine + ex.ToString());
}
timer1.Start();
}
private void buttonStop_Click(object sender, EventArgs e)
{
timer1.Stop();
textBox2.Text = seconds.ToString() + " seconds passed!";
}
private void checkBoxSuperSize_CheckedChanged(object sender, EventArgs e)
{
if (checkBoxSuperSize.Checked == true)
{
label2.Font =
new Font(label2.Font.FontFamily, 40.0F, FontStyle.Bold);
}
else
{
label2.Font =
new Font(label2.Font.FontFamily, 8.25F, FontStyle.Regular);
}
}
}
}
Excellent
Now it is time to test our code. Try running the code by clicking on the Green arrow. Or press F5. You should be presented with a window like this one.
Try to enter a number into the first text box. Press start. See the program running. I'll leave the Super Size checkbox to you to try out. If you press Stop you might get a result similar to mine.
Conclusion
So, in this tutorial we expanded on our windows forms components that we can use. We added a simple timer to our code. Learned that when using a timer we can add to the timer tick event and Visual C# Express will automatically generate some of the code we needed. We also saw how to use a check box and determine if the checkbox is checked or not. We used this to change font styles during the program. We also learned how to change font styles and various other things in the properties tab.
Quite a bit of information, but if you go through the tutorial slowly I think you will find a bunch of useful features that will help you become a little more comfortable with the Visual C# Express program.
[Next Time]- By now I expect that you can create a basic form using the various components. Next time we will skip through the making of the form pretty quickly.
- We will be adding a little bit more code behind the scenes to make our form a bit more useful.
[Later]- If I get good feedback, I will continue these tutorials all the way up to making a simple map hack using some common offsets.
- Please feel free to post your feedback, comments, questions, and other things you might like to see.
- Thanks for reading guys!
[C# Tutorials]