Making Digital Clock In WinForms application

Hi there,

Until today i always thought that building a digital clock is a complex task, well fallas it is not, at least not in WinForms application. Thanx to Timer that make it possible.

Steps to Follow:

1. Create a WinForms application
2. Place a Lable control, name it, i gave him the name lblClock.
3. Find Timer control from ToolBox and place it on your form.
4. Place 2 buttons on the Form, Start and Stop.

Most important event you need to use is the Tick event of TimerTimer has a property called Interval, as i use it inside Start button event. This property will tell the timer that after how long Tick event should be fired, you assign it time in miliseconds, as i set it to 1000 means it will fire after every second and this is the event in which we are going to update our label that will give the effect like a clock is running.

Code to placed inside events are:

a. In Constructor:

        public Form1 ()
        {
            InitializeComponent();

            btnStart.Enabled = true;
            btnStop.Enabled = false;

        }

b. Start Button Click Event

        /// <summary>
        /// start the clock
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStart_Click (object sender, EventArgs e)
        {
            timer1.Enabled = true;
            timer1.Interval = 1000;

            btnStart.Enabled = false;
            btnStop.Enabled = true;

        }

c. Stop Button Click Event

        /// <summary>
        /// stop the clock
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnStop_Click (object sender, EventArgs e)
        {
            timer1.Enabled = false;

            btnStart.Enabled = true;
            btnStop.Enabled = false;

        }


d. Tick Event of Timer

        /// <summary>
        /// this event fires when interval of timer is reached               that in this case is 1000 => 1 sec
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick (object sender, EventArgs e)
        {
            string[] strTime = DateTime.Now.ToString().Split(' ');
            lblClock.Text = strTime[1] + strTime[2];

        }




Comments

Popular Posts