c#定时器

定时器使用的程序。开始---》不断输入aaa  可以停止 继续。


引用:using System.Timers;
 //、、、、、、、、、、、、、、 
  public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            this.Load += Form1_Load;
        }
        //新建定时器。要用System.Timers.Timer。
        //不要用forms.Timer的定时器。这个不精准
        System.Timers.Timer myTimer; 
 
        void Form1_Load(object sender, EventArgs e)
        {
            myTimer =new System.Timers.Timer(2000);//定时周期2秒
            myTimer.Elapsed += myTimer_Elapsed;//到2秒了做的事件
            myTimer.AutoReset = true; //是否不断重复定时器操作
        }
 
        void myTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            richTextBox1.Text = richTextBox1.Text + "\n" + "aaa";
        }
        //开始按钮
        private void button1_Click(object sender, EventArgs e)
        {
            myTimer.Enabled = true; //定时器开始用
            //如果不写下面这句会有一个异常。
            //异常:线程间操作无效: 从不是创建控件"richtextbox"的线程访问它
            //但这不是最好的方法。如果只有一个进程调用richtextbox而已。就可以用下面这句
            //如果有多个线程调用richtextbox等控件。就要用委托。具体百度
            //一篇参考博客http://www.cnblogs.com/zyh-nhy/archive/2008/01/28/1056194.html
            Control.CheckForIllegalCrossThreadCalls = false;
        }
 
        private void button2_Click(object sender, EventArgs e)
        {
            if (myTimer.Enabled)
            {
                myTimer.Enabled = false; //定时器停止
                button2.Text = "continue";
            }
            else
            {
                myTimer.Enabled = true;
                button2.Text = "pause";
            }
        }
 
        private void button3_Click(object sender, EventArgs e)
        {
            myTimer.Close(); //释放Timer占用的资源
            myTimer.Dispose();
            richTextBox1.Text = richTextBox1.Text + "\n" + "over";
        }
    }
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值