C# 定时器

定时器界面:

定时器代码:

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 WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int count = 0;
        int total_time;
        public Form1()
        {
            InitializeComponent();
        }
        // 该函数在窗体加载时执行
        private void Form1_Load(object sender, EventArgs e)
        {
            // 为combobox1添加时间列表
            for (int i = 1; i < 100; i++)
            {
                comboBox1.Items.Add(i.ToString() + "");  // 添加每一列
            }
            comboBox1.Text = "1 秒";  // 设置初始值 }
private void label1_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } // 计时器函数 private void timer1_Tick(object sender, EventArgs e) { ++count; // 自增1 int remaining_time = total_time - count; // 计算剩余时间 label3.Text = remaining_time.ToString() + ""; // 显示剩余时间 progressBar1.Value = count; // 进度条显示的进度 // 如果剩余时间为0,执行 if (remaining_time == 0) { timer1.Stop(); // 停止计时 System.Media.SystemSounds.Asterisk.Play(); // 播放系统声音 MessageBox.Show("计时结束", "提示"); // 弹出框进行提示 } } private void comboBox1_SelectedIndexChanged(object sender, EventArgs e) { // } // 点击button1开始执行该函数 private void button1_Click(object sender, EventArgs e) { string str_time = comboBox1.Text; // 获取combobox1选中的时间 total_time = Convert.ToInt16(str_time.Substring(0, 2)); // 将选中的时间进行转换为整形。Substring(开始下标,截取长度):为截取字符串 progressBar1.Maximum = total_time; // 设置滚动条显示的最大时间 timer1.Start(); // 开启计时 } } }
原文地址:https://www.cnblogs.com/namejr/p/10306500.html