我的代码在这里有什么问题? [英] what is wrong here on my code?

查看:76
本文介绍了我的代码在这里有什么问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨亲爱的

我试图做一个简单的闹钟

我有一个计时器,一个日期时间选择器和一个按钮



代码在这里:



hi dears
I tried to make an simple alarm
I have a timer, a datetimepicker and a button

the code is here:

private void timer1_Tick(object sender, EventArgs e)
        {
            label3.Text = DateTime.Now.ToLongTimeString();

            DateTime dte = DateTime.Now;
            DateTime dts = dateTimePicker1.Value;
            TimeSpan ts = new TimeSpan();
            ts = dts - dte;
            int x = ts.Milliseconds;
            tsec++;
            if (tsec == x)
                MessageBox.Show("gsd");
        }

        private void button1_Click(object sender, EventArgs e)
        {

            timer1.Enabled = true;
            timer1.Interval = 1000;
            timer1.Start();
            
        }





对不起我是非常新的c#



这里有什么问题?

谢谢



excuse me im very new on c#

what is wrong here?
thanks

推荐答案

不要这样做!

试试这个:

Don't do it like that!
Try this:
private bool waitingTimer = true;
private void timer1_Tick(object sender, EventArgs e)
    {
    DateTime now = DateTime.Now;
    label3.Text = now.ToLongTimeString();
    
    if (waitingTimer && now > dateTimePicker1.Value)
        {
        waitingTimer = false;
        MessageBox.Show("gsd");
        }
    }





您的方法存在的问题是它希望计时器一直发生,并准确到毫秒 - 但如果你没有在当前毫秒为零时启动计时器,它永远不会匹配!



The problem with your method is that it expects the timer to happen all the time, and to be accurate to the millisecond - but if you don't start the timer when the current milliseconds is zero, it will never match!


你也可以像这样重写你的代码:



You can also re-write your code like this :

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);




private void timer1_Tick(object sender, EventArgs e)
{
   label3.Text = DateTime.Now.ToLongTimeString();

   long dte = (long) (DateTime.UtcNow - UnixEpoch).TotalMilliseconds;
   long dts = (long) (dateTimePicker1.Value - UnixEpoch).TotalMilliseconds;

    if (dte == dts)
        MessageBox.Show("gsd");

}


这篇关于我的代码在这里有什么问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆