1

I have an application that, when a certain action occurs, the exact DATE/TIME is written as myTime using the Visual studion configuration manager where you can add settings.

This is my setting : Properties.Settings.Default.voteTime

I want as soon as my application starts to show a label that will display "X time left until next vote request"

In my context, the votes must be done each 12 hours so

I want the label to basically show how much time is left from those 12 hours, starting from the voteTime I mentionned above.

I have tried many techniques but I'm a noob at C# and noone worked for me, each time the label either had his default text or was blank...

        DateTime voteTime = Properties.Settings.Default.voteTime;
        DateTime startDate = DateTime.Now;

        //Calculate countdown timer.
        TimeSpan t = voteTime - startDate;
        string countDown = string.Format("{0} Days, {1} Hours, {2} Minutes, {3} Seconds til launch.", t.Days, t.Hours, t.Minutes, t.Seconds);

Above, that is what I tried then I wrote label1.text = countDown;

Thanks in advance.

4

2 回答 2

7

怎么做:

您可以使用System.Windows.Forms.Timer课程来继续显示您的剩余时间。您可以按照以下步骤进行操作:

创建并初始化一个定时器:

Timer timer1 = new Timer();

创建其tick事件方法并设置间隔以更新显示时间:

timer1.Tick += timer1_Tick;
timer1.Interval = 1000; //i am setting it for one second

现在启动计时器:

timer1.Enabled = true;
timer1.Start();

创建timer.tick事件方法并每秒更新标签:

void timer1_Tick(object sender, EventArgs e)
{
    TimeSpan TimeRemaining = VoteTime - DateTime.Now;
    label1.Text = TimeRemaining.Hours + " : " + TimeRemaining.Minutes + " : " + TimeRemaining.Seconds;
}

完整代码:

这是完整的代码。您可以复制并粘贴它:

using System;
using System.Windows.Forms;

namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            timer1.Tick += timer1_Tick;
            timer1.Interval = 1000;
            timer1.Enabled = true;
            timer1.Start();
        }

        Timer timer1 = new Timer();

        void timer1_Tick(object sender, EventArgs e)
        {
            TimeSpan TimeRemaining = VoteTime - DateTime.Now;
            label1.Text = TimeRemaining.Hours + " : " + TimeRemaining.Minutes + " : " + TimeRemaining.Seconds;
        }
于 2013-07-07T11:17:58.813 回答
3

这是一个简单的方法,使用计时器控件,每分钟更新一次标签:

    TimeSpan TimeLeft = new TimeSpan();
    DateTime voteTime = Properties.Settings.Default.voteTime;      
    public Form3()
    {
        InitializeComponent();
        TimeLeft = voteTime - DateTime.Now;
        label1.Text = TimeLeft.ToString(@"hh\:mm") + " til launch.";
        //This value is in milliseconds.  Adjust this for a different time 
        //interval between updates
        timer1.Interval = 60000;
        timer1.Start();
    }
    private void timer1_Tick(object sender, EventArgs e)
    {
        TimeLeft = voteTime - DateTime.Now;
        label1.Text = TimeLeft.ToString(@"hh\:mm") + " til launch.";
    }
于 2013-07-07T05:16:06.073 回答