在特定时间自动刷新窗体c#

时间:2015-11-29 10:20:06

标签: c#

你好,当时间在11:47,19:49之间时,我做这个代码是为了做这个语句(MessageBox.Show("done ");

public Form1()
{   
    InitializeComponent();
    System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
    MyTimer.Interval = (1 * 60 *500 ); // 1 mins
    MyTimer.Tick += new EventHandler(times);
    MyTimer.Start();

}

private void times(object sender, EventArgs e)
{
    DateTime t1 = DateTime.Parse("11:47:00.000");
    DateTime t2 = DateTime.Parse("11:49:00.000");
    TimeSpan now = DateTime.UtcNow.TimeOfDay;
    if (t1.TimeOfDay <= now && t2.TimeOfDay >= now)
    {
       MessageBox.Show("done ");
}

但它没有工作

2 个答案:

答案 0 :(得分:1)

您创建了DateTime和Timespan,其中DateTime是一个时间点,TimeSpan是两个时间点之间的间隔。

还有一秒钟有1000毫秒,所以更好用:

    MyTimer.Interval = (1 * 60 * 1000); // 1 mins

试试这个:

    public Form1()
    {
        InitializeComponent();

        System.Windows.Forms.Timer MyTimer = new System.Windows.Forms.Timer();
        MyTimer.Interval = (1 * 60 * 1000); // 1 mins
        MyTimer.Tick += new EventHandler(times);
        MyTimer.Start();
    }

    private void times(object sender, EventArgs e)
    {
        DateTime t1 = DateTime.Parse("11:47:00.000");
        DateTime t2 = DateTime.Parse("11:50:00.000");
        DateTime now = DateTime.Now;

        if (t1 <= now && t2 >= now)
        {
            MessageBox.Show("done ");
        }
    }

答案 1 :(得分:0)

这是如何让它在11:48触发......

    private System.Windows.Forms.Timer MyTimer;
    private TimeSpan TargetTime = new TimeSpan(11, 48, 0);

    public Form1()
    {
        InitializeComponent();
        MyTimer = new System.Windows.Forms.Timer();
        MyTimer.Interval = (int)MillisecondsToTargetTime(TargetTime);
        MyTimer.Tick += new EventHandler(times);
        MyTimer.Start();
    }

    private double MillisecondsToTargetTime(TimeSpan ts)
    {
        DateTime dt = DateTime.Today.Add(ts);
        if (DateTime.Now > dt)
        {
            dt = dt.AddDays(1);
        }
        return dt.Subtract(DateTime.Now).TotalMilliseconds;
    }

    private void times(object sender, EventArgs e)
    {
        MyTimer.Stop();

        MessageBox.Show("It's " + TargetTime.ToString(@"hh\:mm"));

        MyTimer.Interval = (int)MillisecondsToTargetTime(TargetTime);
        MyTimer.Start();
    }