C# 定时器

早就听过定时器,一直没有用过。真正用的时候发现不会用。尴尬。

遂 来总结一下

首先.NET4.5框架下 建一个Windows窗体应用程序

界面如下

一个字丑。

添加timer1控件。双击进去触发定时器控件。

 1         private void timer1_Tick(object sender, EventArgs e)
 2         {
 3             if (n <5)
 4             {
 5                 n++;
 6                 MessageBox.Show("执行第" + n + "");
 7             }
 8             else
 9             {
10                 timer1.Enabled = false;
11                 MessageBox.Show("一共执行" + n + "次,执行结束");
12             }    
13         }
View Code

定义变量n 为定时器找个停止的点(当n=5)

添加Butten控件 起名Start 

为Start 添加点击事件以触发定时器 也可以在页面加载是触发(Form1_Load()事件)

        private void butten1_Click(object sender, EventArgs e)
        {
            n = 0;
            timer1.Interval = 1000;
            timer1.Enabled = true;
        }
View Code

timer1.Interval = 1000;设置时间间隔以毫秒为单位

timer1.Enabled = true; 控件执行

    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
           
            
        }
        int n = 0;
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (n <5)
            {
                n++;
                MessageBox.Show("执行第" + n + "");
            }
            else
            {
                timer1.Enabled = false;
                MessageBox.Show("一共执行" + n + "次,执行结束");
            }    
        }
        private void butten1_Click(object sender, EventArgs e)
        {
            n = 0;
            timer1.Interval = 1000;
            timer1.Enabled = true;
        }

    }
View Code

完整代码贴上。

以上。

猜你喜欢

转载自www.cnblogs.com/qixiaolan/p/9723276.html