只能开始计时,不能停止计时
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace Count_down
{public partial class Form1 : Form{int count_time = 0; int total_time = 0;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){for (int i = 1; i < 100; ++i) {comboBox1.Items.Add(i.ToString() + " 秒");}//设定一个comboBox的初始值comboBox1.Text = "1 秒";}private void button1_Click(object sender, EventArgs e){total_time = Convert.ToInt16((comboBox1.Text).Substring(0,2));label3.Text = comboBox1.Text;progressBar1.Maximum = total_time;timer1.Start();}private void timer1_Tick(object sender, EventArgs e){count_time++;label3.Text = (total_time - count_time).ToString() + " 秒";progressBar1.Value = count_time;if(count_time == total_time) {timer1.Stop();System.Media.SystemSounds.Asterisk.Play(); //计时结束,系统提示音,也可以加上音乐,那就需要相应的控件去实现MessageBox.Show("计时完成!", "提示");}}}
}
程序运行结果如下:
可以停止计时后继续计时
代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace Count_down
{public partial class Form1 : Form{int count_time = 0; int total_time = 0;public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){for (int i = 1; i < 100; ++i) {comboBox1.Items.Add(i.ToString() + " 秒");}//设定一个comboBox的初始值comboBox1.Text = "1 秒";}private void button1_Click(object sender, EventArgs e){total_time = Convert.ToInt16((comboBox1.Text).Substring(0, 2));progressBar1.Maximum = total_time;if (button1.Text == "开始计时"){label3.Text = (total_time - count_time).ToString() + " 秒"; timer1.Start();button1.Text = "停止计时";}else {timer1.Stop();button1.Text = "开始计时";}}private void timer1_Tick(object sender, EventArgs e){count_time++;label3.Text = (total_time - count_time).ToString() + " 秒";progressBar1.Value = count_time;if(count_time == total_time) {timer1.Stop();timer1.Dispose();System.Media.SystemSounds.Asterisk.Play(); //计时结束,系统提示音,也可以加上音乐,那就需要相应的控件去实现MessageBox.Show("计时完成!", "提示");}}}
}
程序运行结果如下:
总结
我们来说说C#这个控件:
Timer
常用方法(主动):Start() 、Stop()、Dispose();
触发事件(被动):Tick (注意当我们调用Timer组件的Start方法时,每经过Timer的一个Interval(Interval的属性,代表时间间隔,单位是毫秒),就会触发Tick事件。Interval我们可以自己定义,因为我们方便程序显示,时间间隔为1秒,Interval = 1000)。
注意:Timer控件和SerialPort控件一样,也不是可视化的控件。此类的控件还有很多,这里就不一一列举了!