c# 使用定时器Timer

来源:互联网 发布:淘宝不能发布护肤品 编辑:程序博客网 时间:2024/05/20 23:37

定时器使用的程序。开始---》不断输入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";        }    }