项目步骤
1. 创建Windows窗体应用
初始窗体界面如下
2. 添加组件
*在视图中打开工具箱 *
在设计时为了方便调整组件的属性名称,可以选择 视图->其他窗口->文档大纲,文档大纲可以显示各个组件之间的嵌套关系,同时利于修改组件的属性名称。
添加如下组件
- groupbox
- combobox
- button
- textBox
- progressbar
- label
- timer (定时器组件用于实现时基操作)
3. 调整应用界面
定时器组件不会显示在窗体中,在窗体下面显示
上图中标签的显示名称和按钮中的名称可以在选中组件后,在属性面板的text属性中修改
4. 事件绑定
双击组件可以跳转到form.cs文件里,并且生成对应的事件函数,组件的事件函数可以在属性面板中打开闪电选项(即事件选项)看到,如点击事件click对应的事件函数如下
4.1 窗体初始装载事件
窗体装载事件用于在窗体形成开始时配置界面的相关信息
//窗体装载事件
private void Form1_Load(object sender, EventArgs e)
{
//分钟秒钟组合框初始化
byte i;
for (i = 0; i < 60; i++)
{
comboBox1.Items.Add(i.ToString());
comboBox2.Items.Add(i.ToString());
}
//分秒初值设置
comboBox1.Text = "0";
comboBox2.Text = "0";
}
4.2 开始按钮的事件
private void button1_Click(object sender, EventArgs e)
{
switch (Timer_status)
{
case 0:
{
Timer_value = Convert.ToUInt16(comboBox1.Text, 10);
Timer_value *= 60;
Timer_value += Convert.ToUInt16(comboBox2.Text, 10);
if (Timer_value > 0)
{
//开始定时任务
textBox1.Text = Timer_value.ToString() + " S";
button1.Text = "暂停计时";
button1.ForeColor = Color.Green;
button2.Enabled = true;
button2.ForeColor = Color.Red;
comboBox1.Enabled = false;
comboBox2.Enabled = false;
Timer_status = 1;
//设置进度条
progressBar1.Value = 0;
progressBar1.Maximum = Timer_value;
timer1.Start();
}
else
{
System.Media.SystemSounds.Question.Play();
MessageBox.Show("定时时间不能为0", "警告");
}
break;
}
case 1:
{
timer1.Stop();
button1.Text = "继续计时";
Timer_status = 2;
break;
}
case 2:
{
timer1.Start();
button1.Text = "暂停计时";
Timer_status = 1;
break;
}
default: break;
}
}
4.3 停止按钮的事件
//停止按键事件检测
private void button2_Click(object sender, EventArgs e)
{
timer1.Stop();
Timer_count = 0;
Timer_status = 0;
MessageBox.Show("停止计时!", "提示");
button2.Enabled = false;
comboBox1.Enabled = true;
comboBox2.Enabled = true;
button1.Text = "开始计时";
button1.ForeColor = Color.Black;
comboBox1.Text = "0";
comboBox2.Text = "0";
textBox1.Text = "";
progressBar1.Value = 0;
}
4.4 定时器按 interval 时间触发回调函数
定时器按设定的interval时间间隔进行回调函数处理,类似于单片机中的定时器计时满后触发中断函数一样
//定时器事件1
private void timer1_Tick(object sender, EventArgs e)
{
//计数值增加
Timer_count++;
//更新剩余时间
textBox1.Text = (Timer_value - Timer_count).ToString() + " S";
progressBar1.Value = Timer_count;
if (Timer_count == Timer_value)
{
timer1.Stop();
Timer_count = 0;
button1.Text = "计时结束";
System.Media.SystemSounds.Beep.Play();//系统提示音
MessageBox.Show("时间到了!", "提示");
button1.ForeColor = Color.Black;
textBox1.Text = "";
button1.Text = "开始计时";
button2.Enabled = false;
button2.ForeColor = Color.Black;
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox1.Text = "0";
comboBox2.Text = "0";
Timer_status = 0;
progressBar1.Value = 0;
}
}