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事件中添加要执行操作的代码

转载于:https://www.cnblogs.com/zgrh/p/11078340.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值