Home

Progress-Based Controls

 

The Timer

 

Introduction

A timer is a non-spatial object that uses recurring lapses of time in a computer or in your application. To work, every lapse of period, the control sends a message to the operating system. The message is something to the effect of "I have counted the number of lapses you asked me to count".

As opposed to the time that controls your computer, a timer is partly but greatly under your control. Users do not see nor do they use a timer as a control. As a programmer, you decide if, why, when, and how to use this control.

To support timers, the .NET Framework provides the Timer control from the Toolbox and it is implemented through the Timer class. To add it to your application at design time, on the Toolbox, click Timer and click the form.

ApplicationApplication: Introducing the Timer Control

  1. Start a new Windows Application named ScreenSaver1
  2. Change the following properties of the form:
    BackColor: Black
    FormBorderStyle: None
    WindowState: Maximized
  3. In the Properties window, click the Events button Events and double-click MouseMove
  4. Implement the event as follows:
    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 ScreenSaver1
    {
        public partial class Form1 : Form
        {
            static int MoveCounter = 0;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_MouseMove(object sender, MouseEventArgs e)
            {
                Cursor.Hide();
    
                if (MoveCounter == 20)
                    Close();
                MoveCounter++;
            }
        }
    }
  5. Display the form again and, in the Events section of the Properties window, double-click KeyDown
  6. Implement its event as follows:
    private void Form1_KeyDown(object sender, KeyEventArgs e)
    {
                // If the user presses Esc, stop the screen saver
                if (e.KeyCode == Keys.Escape)
                    Close();
    }
  7. Execute the application to test it (to close the form, you will just move the mouse or press Esc)
  8. Display the form

Characteristics of a Timer

A timer is an object used to count lapses of time and send a message when it has finished counting. Each count is called a tick. When a tick occurs, the control fires a Tick event. This Tick event is of type EventArgs, meaning that it doesn't provide more information than to let you know that a lapse has occurred. Here is an example of implementing that event:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : Form
{
    Timer tmrFlash;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        tmrFlash = new  Timer ();
        tmrFlash.Tick += new EventHandler(btnFlashTick);

        Text = "Text Flasher";
        Size = new System.Drawing.Size(435, 88);
    }

    void btnFlashTick(object sender, EventArgs e)
    {
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

The amount of time allocated for counting is called an interval and it is represented by the Interval property. The Interval is a very important characteristic of the Timer control because it measures and controls the total time needed to perform a complete count. The Interval is measured in milliseconds. Like any counter, the lower the value, the faster the count, and the higher the value, the longer the count (if you ask one kid to count from 1 to 10 and you ask another to count from 1 to 20 at the same time, if you ask them to shout when they finish, the first kid would finish first and would shout first). The amount of interval you specify will depend on what you are trying to do. Here is an example of specifying the interval:

void InitializeComponent()
{
    tmrFlash = new  Timer ();
    tmrFlash.Interval = 500;
    tmrFlash.Tick += new EventHandler(btnFlashTick);
}

In order for a timer to count, you must tell it when it should start counting. In some applications, you may want the control to work full-time while in some other applications, you may want the control to work only in response to an intermediate event. The ability to stop and start a Timer control can be set using the Enabled Boolean property. Here is an example of enabling a timer:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : Form
{
    Timer tmrFlash;
    Label lblFlash;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        tmrFlash = new  Timer ();
        tmrFlash.Interval = 500;
        tmrFlash.Enabled = true;
        tmrFlash.Tick += new EventHandler(btnFlashTick);

        lblFlash = new Label();
        lblFlash.AutoSize = true;
        lblFlash.Text = "C# Programming is Fun!!!";
        lblFlash.Font = new System.Drawing.Font("Square721 BT", 24F);
        lblFlash.ForeColor = System.Drawing.Color.Blue;
        lblFlash.Location = new System.Drawing.Point(12, 10);

        Text = "Text Flasher";
        Size = new System.Drawing.Size(435, 88);
        Controls.Add(lblFlash);
    }

    void btnFlashTick(object sender, EventArgs e)
    {
        if (lblFlash.Text == "C# Programming is Fun!!!")
            lblFlash.Text = "";
        else
            lblFlash.Text = "C# Programming is Fun!!!";
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

When, or as soon as, this property is set to true, the control starts counting. You can also make it start by calling the Timer.Start() method. Its syntax is:

public void Start();

If, when, or as soon as, the Enabled property is set to false, the control stops and resets its counter to 0. You can also stop the timer by calling the Timer.Stop() method. Its syntax is:

public void Stop();
 

ApplicationApplication: Using Timer Controls

  1. From the Components section of the Toolbox, click the Timer control Timer and click the form
  2. In the Properties window, set the Enabled property to True and set the Interval to 200
  3. Under the form, double-click the timer
  4. In the top section of the file, under the other using System lines, type using System.Drawing.Drawing2D;
  5. Scroll down and implement the Tick event as follows:
    private void timer1_Tick(object sender, EventArgs e)
    {
            // Get the Graphics object of the form
            Graphics graph = Graphics.FromHwnd(this.Handle);
    
            // Generate a random number
            Random rndNumber = new Random(DateTime.Now.Millisecond);
    
            // Create a list of the colors of the .NET Framework
            Color[] curColor =
            {
    	Color.AliceBlue, Color.AntiqueWhite, Color.Aqua, Color.Aquamarine,
    	Color.Azure, Color.Beige, Color.Bisque, Color.Black,
                    Color.BlanchedAlmond, Color.Blue, Color.BlueViolet,  Color.Brown,
                    Color.BurlyWood, Color.CadetBlue, Color.Chartreuse, Color.Chocolate,
    	Color.Coral, Color.CornflowerBlue, Color.Cornsilk, Color.Crimson,
                    Color.Cyan, Color.DarkBlue, Color.DarkCyan, Color.DarkGoldenrod,
                    Color.DarkGray, Color.DarkGreen, Color.DarkKhaki, Color.DarkMagenta,
    	Color.DarkOliveGreen, Color.DarkOrange, Color.DarkOrchid,
    	Color.DarkRed, Color.DarkSalmon, Color.DarkSeaGreen,
    	Color.DarkSlateBlue, Color.DarkSlateGray, Color.DarkTurquoise,
    	Color.DarkViolet, Color.DeepPink, Color.DeepSkyBlue, Color.DimGray,
    	Color.DodgerBlue, Color.Firebrick, Color.FloralWhite, Color.ForestGreen,
    	Color.Fuchsia, Color.Gainsboro, Color.GhostWhite, Color.Gold,
    	Color.Goldenrod, Color.Gray, Color.Green, Color.GreenYellow,
    	Color.Honeydew, Color.HotPink, Color.IndianRed, Color.Indigo,
    	Color.Ivory, Color.Khaki, Color.Lavender, Color.LavenderBlush,
    	Color.LawnGreen, Color.LemonChiffon, Color.LightBlue,
    	Color.LightCoral, Color.LightCyan, Color.LightGoldenrodYellow,
    	Color.LightGray, Color.LightGreen, Color.LightPink, Color.LightSalmon,
    	Color.LightSeaGreen, Color.LightSkyBlue, Color.LightSlateGray,
    	Color.LightSteelBlue, Color.LightYellow, Color.Lime, Color.LimeGreen,
    	Color.Linen, Color.Magenta, Color.Maroon, Color.MediumAquamarine,
    	Color.MediumBlue, Color.MediumOrchid, Color.MediumPurple,
    	Color.MediumSeaGreen, Color.MediumSlateBlue, Color.MediumSpringGreen,
    	Color.MediumTurquoise, Color.MediumVioletRed, Color.MidnightBlue,
    	Color.MintCream, Color.MistyRose, Color.Moccasin, Color.NavajoWhite,
    	Color.Navy, Color.OldLace, Color.Olive, Color.OliveDrab, Color.Orange,
    	Color.OrangeRed, Color.Orchid, Color.PaleGoldenrod, Color.PaleGreen,
    	Color.PaleTurquoise, Color.PaleVioletRed, Color.PapayaWhip,
    	Color.PeachPuff, Color.Peru, Color.Pink, Color.Plum, Color.PowderBlue,
    	Color.Purple, Color.Red, Color.RosyBrown, Color.RoyalBlue,
    	Color.SaddleBrown, Color.Salmon, Color.SandyBrown, Color.SeaGreen,
    	Color.SeaShell, Color.Sienna, Color.Silver, Color.SkyBlue,
    	Color.SlateBlue, Color.SlateGray, Color.Snow, Color.SpringGreen,
    	Color.SteelBlue, Color.Tan, Color.Teal, Color.Thistle, Color.Tomato,
    	Color.Transparent, Color.Turquoise, Color.Violet, Color.Wheat,
    	Color.White, Color.WhiteSmoke, Color.Yellow, Color.YellowGreen
           };
    
            // Create a list of 10 rectangles for each row
            Rectangle[] row1 = new Rectangle[10];
            Rectangle[] row2 = new Rectangle[10];
            Rectangle[] row3 = new Rectangle[10];
            Rectangle[] row4 = new Rectangle[10];
            Rectangle[] row5 = new Rectangle[10];
            Rectangle[] row6 = new Rectangle[10];
            Rectangle[] row7 = new Rectangle[10];
            Rectangle[] row8 = new Rectangle[10];
    
            // Create the rectangles that will be drawn on the screen
            for (int i = 0; i < 9; i++)
            {
                    row1[i] = new Rectangle(i + (i * (Width / 10)), 0, 
    			(Width - 36) / 10, Height / 8);
    
                    row2[i] = new Rectangle(i + (i * (Width / 10)), 4 + (Height / 8), 
    			(Width - 36) / 10, Height / 8);
    
                    row3[i] = new Rectangle(i + (i * (Width / 10)), 8 + (2 * (Height / 8)), 
    			(Width - 36) / 10, Height / 8);
    
                    row4[i] = new Rectangle(i + (i * (Width / 10)), 12 + (3 * (Height / 8)), 
    			(Width - 36) / 10, Height / 8);
    
                    row5[i] = new Rectangle(i + (i * (Width / 10)), 16 + (4 * (Height / 8)), 
    			(Width - 36) / 10, Height / 8);
    
                    row6[i] = new Rectangle(i + (i * (Width / 10)), 20 + (5 * (Height / 8)), 
    			(Width - 36) / 10, Height / 8);
    
                    row7[i] = new Rectangle(i + (i * (Width / 10)), 24 + (6 * (Height / 8)), 
    			(Width - 36) / 10, Height / 8);
    
                    row8[i] = new Rectangle(i + (i * (Width / 10)), 28 + (7 * (Height / 8)), 
    			(Width - 36) / 10, Height / 8);
            }
    
            // Create the last rectangle of each row
            Rectangle row1a = new Rectangle(9 + (9 * (Width / 10)),
    				   0, ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row2a = new Rectangle(9 + (9 * (Width / 10)),
    	 		   4 + (Height / 8), ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row3a = new Rectangle(9 + (9 * (Width / 10)),
    				   8 + (2 * (Height / 8)), ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row4a = new Rectangle(9 + (9 * (Width / 10)),
    				  12 + (3 * (Height / 8)), ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row5a = new Rectangle(9 + (9 * (Width / 10)),
    				   16 + (4 * (Height / 8)), ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row6a = new Rectangle(9 + (9 * (Width / 10)),
    				   20 + (5 * (Height / 8)), ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row7a = new Rectangle(9 + (9 * (Width / 10)),
    				   24 + (6 * (Height / 8)), ((Width - 36) / 10) - 2, Height / 8);
            Rectangle row8a = new Rectangle(9 + (9 * (Width / 10)),
    				   28 + (7 * (Height / 8)), ((Width - 36) / 10) - 2, Height / 8);
    
            // Create a list of the hatch brushes of the .NET Framework using random colors
            HatchBrush[] curBrush =
            {
    	  new HatchBrush(HatchStyle.BackwardDiagonal, 
    		             curColor[rndNumber.Next(curColor.Length)],
    		             curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.Cross,                                 
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DarkDownwardDiagonal,    
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DarkHorizontal,                   
    			curColor[rndNumber.Next(curColor.Length)],
    			 curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DarkUpwardDiagonal,         
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DarkVertical,                       
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DashedDownwardDiagonal, 
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DashedHorizontal,              
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DashedUpwardDiagonal,    
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DashedVertical,                   
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DashedVertical,                   
    			curColor[rndNumber.Next(curColor.Length)],
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DiagonalBrick,                     
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DiagonalCross,                   
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.Divot,                                  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	 new HatchBrush(HatchStyle.DottedDiamond,                  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.DottedGrid, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.ForwardDiagonal, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Horizontal, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.HorizontalBrick, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LargeCheckerBoard, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LargeConfetti, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LargeGrid, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LightDownwardDiagonal,  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LightHorizontal, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LightUpwardDiagonal, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.LightVertical, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Max, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Min, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.NarrowHorizontal, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.NarrowVertical, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.OutlinedDiamond, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent05,  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent10,  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent20,	
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent25,  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent30,  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent40,  
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent50, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent60, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent70, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent75, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent80, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent90, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Plaid,         
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)]),
    	new HatchBrush(HatchStyle.Percent05, 
    			curColor[rndNumber.Next(curColor.Length)], 
    			curColor[rndNumber.Next(curColor.Length)])
            };
    
            // Draw the rectangles to cover the screen
            for (int i = 0; i < 9; i++)
            {
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row1[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row1[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row2[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row2[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row3[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row3[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row4[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row4[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row5[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row5[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row6[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row6[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row7[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row7[i]);
    
                    graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row8[i]);
                    graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row8[i]);
            }
    
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row1a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row1a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row2a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row2a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row3a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row3a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row4a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row4a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row5a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row5a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row6a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row6a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row7a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row7a);
                graph.FillRectangle(curBrush[rndNumber.Next(curBrush.Length)], row8a);
                graph.DrawRectangle(new Pen(curBrush[rndNumber.Next(curBrush.Length)]), row8a);
    }
  6. Execute the application

The Tick Counter

The Environment class provides a special property used to count a specific number of lapses that have occurred since you started your computer. This information or counter is available through the TickCount property. This property counts the number of milliseconds that have elapsed since you started your computer. Just like the timer control, what you do with the result of this property is up to you and it can be used in various circumstances.

After retrieving the value that the Environment.TickCount property, you can display it in a text-based control. Here is an example:

private void Form1_Load(object sender, System.EventArgs e)
{
	this.textBox1.Text = Environment.TickCount.ToString();
}

ApplicationApplication: Counting the Computer's Ticks

  1. Start a new Windows Application named CompAppElapsedTime1
  2. Design the form as follows:
     
    Tick Counter - Form Design
  3. From the Components section of the Toolbox, click the Timer control Timer and click the form
  4. Change the timer's properties as follows:
    Interval:20
    Enabled: True
  5. Double-click an unoccupied area of the form to generate its Load event
  6. Declare a global private integer named CompTime and initialize it in the Load event as follows:
     
    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 CompAppElapsedTime1
    {
        public partial class Form1 : Form
        {
            private int CompTime;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                CompTime = Environment.TickCount;
            }
        }
    }
  7. Return to the form
  8. Double-click the timer1 control and implement its Timer event as follows:
     
    private void timer1_Tick(object sender, EventArgs e)
    {
            int CurTickValue = Environment.TickCount;
            int Difference = CurTickValue - CompTime;
    
            label1.Text = string.Format("This computer has been ON for {0}",
                                                       CurTickValue.ToString());
            label2.Text = string.Format("This application has been running for {0}",
                                                        Difference.ToString());
    }
  9. Return to the form and double-click the Close button
  10. Implement the event as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
            Close();
    }
  11. Test the application
     
    Tick Counter - Counting the elapsed time
  12. After testing the application, close it
  13. To make the values easier to read, change the code of the OnTimer event as follows:
    private void timer1_Tick(object sender, EventArgs e)
    {
            int curTickValue = Environment.TickCount;
            int difference = curTickValue - CompTime;
    
            int computerHours, computerMinutes, computerSeconds;
            int applicationHours, applicationMinutes, applicationSeconds;
    
            computerHours = (curTickValue / (3600 * 999)) % 24;
            computerMinutes = (curTickValue / (60 * 999)) % 60;
            computerSeconds = (curTickValue / 999) % 60;
    
            applicationHours = (difference / (3600 * 999)) % 24;
            applicationMinutes = (difference / (60 * 999)) % 60;
            applicationSeconds = (difference / 999) % 60;
    
            label1.Text = string.Format("This computer has been ON for {0} hours, {1} minutes {2} seconds",
                                            computerHours.ToString(),
                                            computerMinutes.ToString(),
                                            computerSeconds.ToString());
    
            label2.Text = string.Format("This application has been running for {0} hours, {1} minutes {2} seconds",
                                            applicationHours.ToString(),
                                            applicationMinutes.ToString(),
                                            applicationSeconds.ToString());
    }
  14. Execute the application to test it:
     
    Tick Counter - Easier to read
  15. After testing the application, close the form

Introduction to Progress Bars

 

Description

A progress bar is a control that displays (small) rectangles that are each filled with a color. These (small) rectangles are separate but adjacent each other so that, as they display, they produce a bar. To have the effect of a progress bar, not all these rectangles display at the same time. Instead, a numeric value specifies how many of these (small) rectangles can display at one time.

Creating a Progress Bar

To support progress bars, the .NET Framework provides the ProgressBar class, which is derived from the Control class. In the Toolbox, the progress bar is represented by the ProgressBar control. At design time, to get a progress bar, from the Common Controls section of the Toolbox, you can click the ProgressBar control and click the form (or another container).

To programmatically get a progress bar, declare a variable of type ProgressBar, use the new operator to allocate memory for it, and add it to the Controls property of its container. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    ProgressBar progress;

    public Exercise()
    {
        InitializeComponent();
    }

    private void InitializeComponent()
    {
        Text = "Progressive Studies";
        Size = new Size(242, 80);

        progress  = new ProgressBar ();

        Controls.Add(progress);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

This would produce:

Progress Bar

ApplicationApplication: Introducing Progress Bars

  1. Start a new Windows Application named ProgressClock1
  2. Design the form as follows:
     
    Progressive Clock - Form Design
     
    Control Text Name Other Properties
    Label Label Time   Anchor: Right
    Label Label Hours:    
    ProgressBar ProgressBar 00   Anchor: Left, Right
    Label Label   lblHours  
    Label Label Minutes:    
    ProgressBar  ProgressBar     Anchor: Left, Right
    Label Label 00 lblMinutes Anchor: Right
    Label Label Seconds:    
    ProgressBar  ProgressBar     Anchor: Left, Right
    Label Label 00 lblSeconds Anchor: Right
    Button Button Close btnClose Anchor: Right
    Timer Timer     Enabled: True
    Interval: 20
  3. Save all

Characteristics of a Progress Bar

 

Introduction

The progress bar shares the various characteristics of other graphical controls (that is, the objects derived from the Control class). These include the location, the size, the back color, the size, the cursor, the ability to be anchored, the ability to the docked, the ability to be shown or hidden, and the ability to be enabled or disabled, etc.

Here is an example:

private void InitializeComponent()
{
        Text = "Progressive Studies";
        Size = new Size(282, 80);

        progress  = new ProgressBar ();
        progress.Location = new Point(12, 12);
        progress.Width = 252;

        Controls.Add(progress);
}

This would produce:

Progress Bar

After adding it to an application, a progress bar assumes a horizontal position (the actual progress bar of Microsoft Windows, as implemented in Win32, can also have a vertical orientation; the .NET Framework's version has this and other limitations).

The Minimum and Maximum

To show its effect, the progress bar draws its small rectangles as a bar. These small rectangles are from a starting position to an ending position. This means that the progress bar uses a range of values. This range is controlled by the Minimum and the Maximum properties whose default values are 0 and 100 respectively. At design time, you can set them using the limits of an integer. To programmatically set these values, assign the desired numbers to one or both. Here is an example:

private void InitializeComponent()
{
        Text = "Progressive Studies";
        Size = new Size(282, 80);

        progress  = new ProgressBar ();
        progress.Location = new Point(12, 12);
        progress.Width = 252;

        progress.Minimum = 0;
        progress.Maximum = 255;

        Controls.Add(progress);
}

The small rectangles would be drawn from the left (the Minimum value) to the right (the Maximum value) sides of the control.

The Value of a Progress Bar

At one particular time, the most right rectangle of a progress bar is referred to as its position and it is represented by the Value property. At design time, to set a specific position for the control, change the value of the Value property whose default is 0. The position must always be between the Minimum and Maximum values. At design time, if you change the Minimum to a value higher than the Value property, the value of Value would be increased to the new value of Minimum. If you set the value of Value to a value lower than the Minimum, You would receive an error. After clicking OK, the value of the Minimum would be reset to that of the Value property. In the same way, if you set the value of Value to a value higher than Maximum, you would receive an error.

At run time, you can assign the desired value to the Value property. Once again, avoid specifying a value that is out of range. Here is an example:

private void InitializeComponent()
{
        Text = "Progressive Studies";
        Size = new Size(282, 80);

        progress  = new ProgressBar ();
        progress.Location = new Point(12, 12);
        progress.Width = 252;

        progress.Minimum = 0;
        progress.Maximum = 255;

        progress.Value = 88;

        Controls.Add(progress);
}

This would produce:

Progress Bar

The Step Value of a Progress Bar

Because a progress bar is usually meant to indicate the progress of an activity, when drawing its small rectangles, it increases its current position in order to draw the next rectangle, except if the control is reset. The number of units that the object must increase its value to is controlled by the Step property. By default, it is set to 10. Otherwise, you can set it to a different value of your choice. Here is an example:

private void InitializeComponent()
{
        Text = "Progressive Studies";
        Size = new Size(282, 80);

        progress  = new ProgressBar ();
        progress.Location = new Point(12, 12);
        progress.Width = 252;

        progress.Minimum = 0;
        progress.Maximum = 255;
        progress.Value = 88;

        progress.Step = 12;

        Controls.Add(progress);
}

When the control draws one of its rectangles based on the Step value, it calls the PerformStep(). Its syntax is:

public void PerformStep();

After a small rectangle has been drawn, the current value is incremented by the value of the Step property. If you want to increase the value of the control to a value other than that of the Step property, you can call the Increment() method. Its syntax is:

public void Increment(int value);

The amount by which to increment is passed to the method. Here is an example:

using System;
using System.Drawing;
using System.Windows.Forms;

public class Exercise : System.Windows.Forms.Form
{
    ProgressBar progress;
    Button btnIncrement;

    public Exercise()
    {
        InitializeComponent();
    }

    void InitializeComponent()
    {
        Text = "Progressive Studies";
        Size = new Size(284, 115);

        progress  = new ProgressBar ();
        progress.Location = new Point(12, 12);
        progress.Width = 252;

        progress.Minimum = 0;
        progress.Maximum = 255;
        progress.Value = 88;
        progress.Step = 12;

        btnIncrement = new Button();
        btnIncrement.Text = "Increment";
        btnIncrement.Location = new Point(12, 52);
        btnIncrement.Click += new EventHandler(btnIncrementClick);

        Controls.Add(progress);
        Controls.Add(btnIncrement);
    }

    void btnIncrementClick(object sender, EventArgs e)
    {
        progress.Increment(8);
    }
}

public class Program
{
    static int Main()
    {
        System.Windows.Forms.Application.Run(new Exercise());
        return 0;
    }
}

ApplicationApplication: Using Progress Bars

  1. Change the properties of the progress bar controls as follows:
     
    Name Maximum Step
    pgrHours 23 1
    pgrMinutes 59 1
    pgrSeconds 59 1
  2. Double-click the timer control to generate its Tick event and implement it as follows:
     
    private void timer1_Tick(object sender, EventArgs e)
    {
                // Get the current time
                DateTime curTime = DateTime.Now;
                // Retrieve the hour value of the current time
                int H = curTime.Hour;
                // Retrieve the minute value of the current time
                int M = curTime.Minute;
                // Retrieve the second value of the current time
                int S = curTime.Second;
    
                // Draw the progress boxes based on the values of the time
                pgrHours.Value = H;
                pgrMinutes.Value = M;
                pgrSeconds.Value = S;
    
                // Display the values in the corresponding labels
                lblHours.Text = H.ToString();
                lblMinutes.Text = M.ToString();
                lblSeconds.Text = S.ToString();
    }
  3. Double-click the Close button and implement it as follows:
     
    private void btnClose_Click(object sender, EventArgs e)
    {
            Close();
    }
  4. Execute the application to test it then close the form:
     
    Progressive Clock
  5. Close the form and return to your programming environment

The Style of a Progress Bar

So far, we have described a progress bar as drawing small rectangles to represent the control. These rectangles are visually distinct (don't touch each other) and adjacent. As an alternative, if you want the progress control to appear smooth, you can make the control draw each next rectangle exactly where the previous one stops. To support this characteristic, the ProgressBar class is equipped with the Style property.

The ProgressBar.Style property is based on the ProgressBarStyle enumeration that has three members:

If you decide to use the Marquee style, the progress bar will continually show its animation of small rectangles moving at a speed set from the MarqueeAnimationSpeed integral property and you cannot get the value of the progress bar.

ApplicationApplication: Configuring Progress Bars

  1. On the form, click the top progress bar
  2. Press and hold Ctrl
  3. Click the other two progress bars
  4. Release Ctrl
  5. In the Properties window, click Style, click the arrow of its combo box, and select Continuous
  6. Execute the application to see the result
     
    Progressive Clock
  7. Close the form and return to your programming environment

Previous Copyright © 2004-2010 FunctionX, Inc. Next