How to Activate Timer in an Application (Timer Class) Using C#

Introduction

This article shows how to activate a Timer in an application using the "Timer" class in C#. A Timer actually helps us to raise certain events at a fixed interval of time.
Since it is a demo application we will just show a Message Box in every timer time interval, using this concept you can easily implement a Timer in your own application.

Procedure

Step 1

Create a New “Windows Form Application” in Visual Studio and name it as you choose (I here named it TimerControl).
Now a new Form is created.

Step 2

Add two Button Controls to your form and resize the window, also change the text of the Button Controls to "Start Timer" and "Stop Timer" to start and stop the timer respectively. Your form will look like this:

Timer App in Windows

Step 3

From the toolbox add the "Timer" control (for the Timer Class) to your project.

Step 4

Now add the "Start Timer" Button Click Event to your project and in that add the following code:

private void buttonStart_Click(object sender, EventArgs e)

{

    //Adding the Time Interval in which the Timer is Ticked

    // I have here initialize the timer with Time Interval of 5 seconds

    // (1000) is multiplied because by default it will take values in 

    // milliseconds

    // so we are just passing 5000 ms

    timer1.Interval = (1000) * 5;

 

    //Calling the Start Method to start the Timer

    timer1.Start();

 

    //Creating the Event which is raised in that certain time Interval 

    timer1.Tick += new EventHandler(timer1_Tick);

 

    //Showing the Conformation that Timer is Started

    MessageBox.Show("Timer is Started");

}

As we can see, an Event "Tmer_Tick" is created in our project in which you can add whatever code you want to be executed on every specified interval. Here I am only showing a Message Box on every time interval, so add the following line of code for the "Timer_Tick" Event:

void timer1_Tick(object sender, EventArgs e)

{

    //Showing the Message in whenever the Event is raised

    MessageBox.Show("5 second is Completed");

}

Step 5

Now it's all about how to start the timer and raise the event for every time certain time interval, now if we want to stop that timer then what we need to do is to just call the stop method of the timer class.
So add the "Stop Timer" Button Click Event to your project and add the following line of code:

private void buttonStop_Click(object sender, EventArgs e)

{

    //Stop the Timer

    timer1.Stop();

    MessageBox.Show("Timer is Stoped!!!");

 

}

Step 6

That's all; just build it and run your project, after clicking the "Start Timer" Button you will see that a Message Box is displayed every 5 seconds. If you want to stop that, just press the "Stop Timer" Button and your timer will be stopped.
That's all for this article. I am embedding the Source File so that you can go through it.

Thank You.


Similar Articles