0. 环境搭建
首先要确保你的VS安装了.Net桌面开发,安装了之后直接新建项目。
未安装的话打开VS Installer,勾选上.Net桌面开发后,开始安装。
安装成功后新建项目。
1. 新建项目
1.1 选择语言
语言选择C#,然后选中Windows窗体应用(.Net Framework),点击下一步。
1.2 配置项目
输入项目名称,选择项目的位置,选择开发框架后,点击创建。
2. 项目实现
2.1 配置Form1.cs[设计]文件
在**Form1.cs[设计]**中放入如下控件,并在对应的属性框中设置好属性。
注意的是,这里需要添加一个隐藏控件:定时器(timer)
设置定时器的属性时需要注意:
- Enabled要设置为False。
- Interval要设置为1000。(在这里,Interval的单位是ms,因此1000ms就是1s)
2.2 配置Form1.cs文件
Form1.cs的代码如下所示
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 Countdown
{
public partial class Form1 : Form
{
int count; //用于定时器(timer1)计数
int time; //存储设定的倒计时时间
public Form1() //构造体
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
int i;
for (i = 1; i <= 99; i++)
{
comboBox1.Items.Add(i.ToString() + " s"); //初始化下拉框的内容为"1 s" ~ "99 s"
}
comboBox1.Text = "1 s";
}
private void timer1_Tick(object sender, EventArgs e) //timer1事件
{
count++; //软件计时器在定时器每过1秒的时候加1(定时器每过x毫秒进入此函数,x要在设计中的timer1的interval属性中设置)
label3.Text = (time - count).ToString() + "s"; //倒计时时间减去软件计数器的时间,即剩余时间
progressBar1.Value = count; //设置进度条进度
if (count == time) //当软件计数器的值和倒计时时间相等时
{
timer1.Stop(); //停止计时
System.Media.SystemSounds.Asterisk.Play(); //提示音
MessageBox.Show("Time Over", "end"); //提示框,","前是显示的内容,","后是提示框的标题
count = 0;
}
}
private void button1_Click(object sender, EventArgs e) //Start按钮事件
{
string str = comboBox1.Text; //将下拉框中显示的内容赋值给变量str
string data = str.Substring(0, 2); //因为str中既有数字,又有字母,而程序只需要字母,因此使用Substring函数提取数字,第一个参数
//的意思是从第0位开始,第二个参数的意思是从第一个参数的位置开始往后提取2个字符。
time = Convert.ToInt16(data); //将提取到的数字从字符型转换为整形
progressBar1.Maximum = time; //将数字赋值给进度条的最大值
timer1.Start(); //开始定时
}
}
}
3. 简易倒计时器预览
4. 参考
参考了杜洋工作室的入门C#设计视频。