使用c#编写定时器程序
这是我第一个C#程序,是在B站跟着杜洋学习的,他的视频风格是比较愉快的,而且很生动仔细,一教一学的方式,感觉很好,希望我玩的开心!
创建工程
为窗口添加窗体部件
为窗口内部添加逻辑
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)//在启动exe程序后,显示窗口之前,执行的语句
{
int i;
for (i = 1; i < 50; i++)
{
comboBox1.Items.Add(i.ToString() + " 秒");//为下拉输入的box添加选项
}
label3.Text = "0秒"; //为label(标签),添加文字
}
private void Timer1_Tick(object sender, EventArgs e)//相当于单片机中的定时器中断函数,这里的是1000ms,即1s作为一个周期,1s运行一次该程序
{
count++; //每秒钟加一,相当于现在时间的秒数
label3.Text = (time -count).ToString() + "秒"; //计算剩余秒数(时间),并且显示到标签
progressBar1.Value = count; //将时间数设为进度条的进度量,每秒发生一次改变,效果为进度条逐渐上升
if (count == time)
{
timer1.Stop();
System.Media.SystemSounds.Asterisk.Play();
MessageBox.Show("时间到了!", "提示");
//结束这一次的计时
//为下一次计时做准备
progressBar1.Value = 0;//初始化进度条最大容量
button1.Text = "开始计时";//初始化按钮显示内容1
count = 0;
time = 0;
}
}
private void Button1_Click(object sender, EventArgs e)//单击按下按钮后,需要执行的程序
{
if (button1.Text == "开始计时")
{
time = Convert.ToInt16(comboBox1.Text.Substring(0, 2));//转化成10进制
progressBar1.Maximum = time;//进度条开始的数值,即进度条最大数值
timer1.Start();//开始计时
button1.Text = "停止计时";
}
else
{
button1.Text = "开始计时";
timer1.Stop();//停止计时
}
}
private void Label3_Click(object sender, EventArgs e)
{
}
private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}