目录
本实例演示Timer控件的用法:Timer控件主要用于需要进行时间间隔控制的场合。
Timer控件的Enable默认为False,当其值变为True时,每隔一段时间就会发生一次Timer的Tick事件。Tick事件的时间间隔有Interval属性设置,默认值为100,以毫秒为单位。
一、【程序实现】
步骤1、先设计窗口,把各种需要的控制布局在窗口内
步骤2、制定应用的功能方案
本实例需要添加一个“timer控件”:
(1)、首先,我们需要按下按键,开始计时,进度条与时间同步,
(2)、按下按键2停止计时
所需控件:
控件 | 控件名称 | 功能 |
1 | ProgressBar | 进度条 |
2 | button | 按键 |
3 | comboBox | 下拉框 |
4 | timer | 定时器 |
5 | label | 标签 |
步骤3、制定后台逻辑
具体程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
//定义全局变量
int count;
int time;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int i;
//计时范围(0-99)
for (i = 1; i < 100;i++)
{
comboBox1.Items.Add(i.ToString() + "秒");
//初始化下拉框内容(数字后加一个空格便于布局)
}
label3.Text = "";
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
//Timer控件,计时器事件
private void timer1_Tick(object sender, EventArgs e)
{
//记录当前秒数
count++;
label3.Text = (time - count).ToString() + "秒";
//显示剩余时间
//控件label3的属性文本.Text中显示(time - count).ToString() + "秒"
progressBar1.Value = count;
//设置进度条精度
//精度条控件 progressBar1的值Value设置为变量count
//这个是通过中断更新的,刚才已经设计为1000ms
if (count == time)
{
//时间到,停止计时
timer1.Stop();
System.Media.SystemSounds.Asterisk.Play();
//提示音
MessageBox.Show("时间到了!", "提示");
//弹出提示框
}
}
//开始计时按钮事件
private void button1_Click(object sender, EventArgs e)
{
string str=comboBox1.Text;
//将下拉框内容添加到变量str
string date=str.Substring(0, 2);
//0:从头开始查,查两位,比如查99秒,第三位就不查,
//如果是“秒99”,从1开始查
//如果“108秒”查3位
//这里就提取了字符,比如说“10”,这是字符串来的
time = Convert.ToInt16(date);
//得到设定定时值(整型)
//一个类Convert.:把一个字符串date转换为一个变量time(使用16位的整型)
progressBar1.Maximum = time;
//进度条最大数值
//控件 progressBar1的属性.Maximum(最大值)设为time
timer1.Start();
//开始计时
}
//停止计时事件
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
//停止计时
System.Media.SystemSounds.Asterisk.Play();
//提示音
MessageBox.Show("停止计时!", "提示");
//弹出提示框
}
}
}
二、【运行效果】
运行程序,测试功能效果如下: