功能:实现下拉框选择时间(5秒至500秒),启动后倒计时,途中可暂停,继续启动。
代码:
namespace test
{
public partial class Form1 : Form
{
int count;//计数
int time;//存储定时器
bool isCount;//判断是否启动,false停止,true启动。
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
for(int i = 5; i <= 500; i+=5)
{
comboBox1.Items.Add(i.ToString() + "秒");//下拉框
}
comboBox1.Text = "5秒";
label3.Text = "0秒";
}
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.Beep.Play();//提示音效
MessageBox.Show("时间到了!", "提示");//弹窗提示
progressBar1.Value = 0;
count = 0;
isCount = false;
button1.Text = "启动";//改按钮显示文本
}
}
private void button1_Click(object sender, EventArgs e)//按钮事件
{
if(isCount)
{
//暂停
timer1.Stop();
button1.Text = "继续";
isCount = false;
}
else
{
//启动、继续
if(count == 0)
{
string str = comboBox1.Text;//下拉框的取值赋值str
int num = str.Length - 1;
time = Convert.ToInt32(str.Substring(0, num));//固定长度
progressBar1.Maximum = time;//进度条取time
}
timer1.Start();
isCount = true;
button1.Text = "暂停";
}
}
}
}
控件记录:
- 定时器:timer
- 下拉框:combobox
- 下拉框可以通过属性添加内容
- 进度条:progressbar
- 文本:label