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