Yesterday I was working on one of my applications that needs to include a digital clock. So I was looking for an easy way or a small piece of code to include it. From Googling, I saw that there is plenty of code available but unfortunately almost all of it contains a lot of time consuming code. So then I tried myself and did it by few lines. That's why I come here to share this with those friends who are beginners in C#, not for experts.
Much introduction here, so let's start.
1. Create a new Windows Forms Application project. Name the project as you wish.
2. Then go to the form's design view. Our form will look such as below:
It contains a label at the center of the form and a timer control. So drag a label and a timer from the toolbox onto the form. Change the color of the label and expand it's text size.
3. Right-click on the form and select view code. In this page, write your timer_tick event for the timer control that you selected from the toolbox. This is the most important part here. Have a look:
private void timer1_Tick(object sender, EventArgs e)
{
label1.Text = DateTime.Now.ToString("HH:mm:ss");
}
Here DateTime represents an instance of a time of a day and Now represents the current date and time of your computer. HH:mm:ss represents the time format as you wish to display it in this format.
4. Most functions are complete, but as a clock it should dynamically change it's time. Correct? For that we don't use any code here. Right-click on the timer control of design page and go to properties. Change the Interval and set it to 1.
Your clock is ready to operate..!! That's the end today. Happy Coding..