C#: 设计一个定时器


第一步: 在VS中,可以进行桌面软件样式布局的设计

 

 

 

 

第二步:在控件列表中,双击Timer,即可为程序设置了一个计时器组件

 

 设置计时器的刷新时间:1s

 

 

 

 

 // (推荐)在程序中设置初始值: comboBox1.Text = "1 秒";

第三步:编写定时器代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        int count;//用于定时器计数
        int time;//存储设定的定时值
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) { int i; for (i = 1; i < 100; i++)//计数范围(0-99)
 { comboBox1.Items.Add(i.ToString() + "");//初始化下拉框内容(数字后加一个空格便于程序处理)
 } comboBox1.Text = "1 秒"; } 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.Asterisk.Play();//提示音
                MessageBox.Show("时间到了!!!","提示!!");//弹出提示框
 } } private void button1_Click(object sender, EventArgs e)//开始计时按钮事件
 { string str = comboBox1.Text;//将下拉框内容添加到一个变量中
            string data = str.Substring(0, 2); time = Convert.ToInt16(data);//得到设定定时值(整形)
            progressBar1.Maximum = time;//进度条最大数值
            timer1.Start();//开始计时
 }


    }
}

 

 

效果:

 

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM