C#工控上位机——倒计时计时器
第一步:找出需要的工具
第二步:对工具进行布局
第三步:修改各个工具的属性
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 WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
//窗口运行时的主函数
private void Form1_Load(object sender, EventArgs e)
{
int i;
for (i = 1;i < 100;i++)
{
//comboBox1是下拉列表的名字;Items是comboBox1的属性;Add是一个函数
comboBox1.Items.Add(i.ToString() + "秒");
}
}
}
}
设计定时器
双击进入事件函数
private void button1_Click(object sender, EventArgs e)
{
//timer1是定时器的名称
timer1.Start();//启动计时器
}
最后的程序
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 WindowsFormsApp1
{
public partial class Form1 : Form
{
int count;//定义全局变量
int time;
public Form1()
{
InitializeComponent();
}
//窗口运行时的主函数
private void Form1_Load(object sender, EventArgs e)
{
int i;
for (i = 1;i < 100;i++)//下拉列表显示的范围(0-99)
{
//comboBox1是下拉列表的名字;Items是comboBox1的属性;Add是一个函数
comboBox1.Items.Add(i.ToString() + " 秒");//注意秒之前有一个空格
}
}
//定时器事件
private void timer1_Tick(object sender, EventArgs e)
{
count++;//记下当前秒
label3.Text = (time - count).ToString() + "秒";//显示剩余时间(将数字整型转化为字符串型)
progressBar1.Value = count;//设置进度条的值为计数值
if (count == time)//当计数到最大值时
{
timer1.Stop();//停止计时器
System.Media.SystemSounds.Asterisk.Play();//提示音
MessageBox.Show("时间到了!");//弹出提示框
}
}
//开始按钮事件
private void button1_Click(object sender, EventArgs e)
{
//获取下拉框中的字符串
string str = comboBox1.Text;
string data = str.Substring(0, 2);//截去str的二个字符串
time = Convert.ToInt16(data);//将下拉列表中的字符串装换为整形储存在全局变量time中
progressBar1.Maximum = time;//progressBar1进度条的名字,Maximum进度条的属性,最大值为time的值
//timer1是定时器的名称
timer1.Start();//启动计时器
}
}
}