C# Winfrom 簡單的運用Timer控件


   注意,在使用DateAndTime時,需要添加引用 using Microsoft.VisualBasic;否則不可以計算時間之間的差值。

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;

using Microsoft.VisualBasic;

namespace DJS {
    public partial class Form1 : Form {

        DateTime dtNow, dtSet;
        public Form1() {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e) {
            if(button1.Text=="設置") {
                button1.Text = "停止";
                timer2.Start();
            }
            else if(button1.Text=="停止") {
                button1.Text = "設置";
                timer2.Stop();
                label7.Text = "倒計時已取消";
            }
        }

        private void timer1_Tick(object sender, EventArgs e) {
            label2.Text = DateTime.Now.ToLongTimeString();//顯示系統時間
            dtNow = Convert.ToDateTime(label2.Text);
        }

        private void timer2_Tick(object sender, EventArgs e) {
            //記錄設置的到期時間
            dtSet = Convert.ToDateTime(numericUpDown1.Value + ":" + numericUpDown2.Value + ":" + numericUpDown3.Value);
            long countdown = DateAndTime.DateDiff(DateInterval.Second, dtNow, dtSet, FirstDayOfWeek.Monday, FirstWeekOfYear.FirstFourDays);
            if(countdown>0) {  //判斷倒計時是否大於0
                label7.Text="倒計時已設置,剩余"+ countdown + "";
            }
            else {
                label7.Text = "倒計時已到";
            }
        }

        private void Form1_Load(object sender, EventArgs e) {
            timer1.Interval = 1000;
            timer1.Enabled = true;
            numericUpDown1.Value = DateTime.Now.Hour;
            numericUpDown2.Value = DateTime.Now.Minute;
            numericUpDown3.Value = DateTime.Now.Second;
        }
    }
}
View Code

Timer控件又稱為計時器組件,可以定期引發事件,時間的間隔的長度用interval屬性定義,其屬性值為毫秒為單位,每個時間間隔會自動觸發tick事件,開發人員可以在tick事件中添加要執行操作的代碼


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM