簡體   English   中英

如何建立倒數計時器

[英]how to create a countdown timer

我想創建一個說56小時的倒計時計時器,該計時器將在我的應用程序上動態顯示倒計時。兩次重啟之間也應該保持不變,即如果重啟之前我的計時器顯示經過了3個小時,那么重啟后應該從3個小時開始而不是重置。我使用了這種方法,將當前日期+ 56小時寫入文本文件,然后將其用作參考,但是問題是“ label6”上顯示的倒數不會超過24小時(我希望它顯示倒計時表格56:00:00,然后最多00:00:00)如果還有其他方法,請分享..謝謝

我的代碼:

public void timer()
    {
        string path1 = userdir + username + app + file;

        string triggerfile = path1;
        if (!File.Exists(triggerfile))
        {
            string ss = (DateTime.Now.AddHours(56).ToString());

            System.IO.File.WriteAllText(triggerfile, ss);
        }
        using (StreamReader sr = File.OpenText(triggerfile))
        {
            triggerdate = DateTime.Parse(sr.ReadToEnd());
        }
        var st = triggerdate;

        var timer = (new Timer() { Interval = 1000 });
        timer.Tick += (obj, args) => label6.Text = (TimeSpan.FromSeconds(20) - (st - DateTime.Now)).ToString("hh\\:mm\\:ss");
        timer.Enabled = true;

        if (DateTime.Now >= triggerdate)
        {

            label17.Text = "Times up";
            MessageBox.Show("YOU ARE PAST YOUR TRIAL HOURS..");
        }
    }

可能是這樣的:

    var currentTime = (triggerdate.Subtract(DateTime.Now));
    string remainingTime = "" + (currentTime.Days*24 + currentTime.Hours) + ":" + currentTime.Minutes + ":" + currentTime.Seconds);

    var timer = (new Timer() { Interval = 1000 });
    timer.Tick += (obj, args) => label6.Text = remainingTime;
    timer.Enabled = true;

當您向日期添加56小時時,添加2天8小時是相同的。 您必須將DateTime的日期轉換為小時,然后將此小時添加到DateTime的小時中,以獲取總小時數。

希望對您有幫助。

您可以使用TimeSpanTotalHours屬性

TimeSpan remaining = ... ; // compute remaining time
string label = string.Format("{0}:{1:mm\\:ss}", (int) remaining.TotalHours, remaining);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM