The use of C# timer Timer

    In programming, we often encounter some periodic execution operations. For example, a social program requires that the list be refreshed every 2 seconds. For example, when the program displays the time, the time needs to be refreshed every 1 second. Using the Timer timer, the following uses the C# programming language to develop a real-time display time electronic watch program as an example to introduce the use of the Timer timer.

    The final program effect of the electronic watch is shown in the figure:


(1) To create a WPF program, you can also use visual studio to create a WPF program. For the convenience of interface beautification, I use Expression blend to create the program, as shown in the figure:


(2) Select the window and check the AllowsTransParency property to remove the outer border of the window


(3) Modify the background color


(4) Drag in a Label control


(5) Change the size of the form, then define the name of the Lable control as Show_Time and set the color of the content of the Lable control


(6) Set the alignment of the Label content and modify the font size


(7) Write the timer code in the main window class


Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
namespace WPFtimer
{
	/// <summary>
	/// Interaction logic of MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{
			this.InitializeComponent();
            
			 DispatcherTimer timer=new DispatcherTimer();//Create timer timer
			 timer.Interval = TimeSpan.FromMilliseconds(1000);//Set the period to 1000 milliseconds
             timer.Tick += new EventHandler(Refresh_Time);
			 timer.Start ();
		}
		
		public void Refresh_Time(object sender, EventArgs e)
		{
		  string time=DateTime.Now.ToString("hh:mm:ss");//Get system time
		  this.show_time.Content=time;//Refresh the content of Lable
		}
	}
}
Like friends, like, I hope you will support and pay attention

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325205685&siteId=291194637