在一定时间范围内活动

本文关键字:活动 范围内 定时间 | 更新日期: 2023-09-27 18:02:17

在c#中是否有办法在一定时间范围内激活消息框?例如,我可以有一个在13:00和16:00出现的消息框吗?

if(DateTime.TimeOfDay(13,0,0 to 16,0,0)
{
    messagebox.show("You need to feed the dog now");
}

如果你有解决这个问题的方法,请告诉我,因为我已经被这个问题困了一段时间了。

这是我到目前为止的代码。

if(theDate.TimeOfDay <= new TimeSpan(11,59,0))
            {
                synthesizer.SpeakAsync("Good Morning");
            }
            else if(theDate.TimeOfDay >= new TimeSpan(17, 0, 0))
            {
                synthesizer.SpeakAsync("Good Evening");
            }
            else if(theDate.TimeOfDay > new TimeSpan(12, 0, 0) && theDate.TimeOfDay < new TimeSpan(16, 59, 0))
            {
                synthesizer.SpeakAsync("Good Afternoon.");
            }

在一定时间范围内活动

您可以轻松地使用<>运算符来比较TimeSpan值,如;

var ts = DateTime.Now.TimeOfDay;
if(ts > new TimeSpan(13, 0, 0) && ts < new TimeSpan(16, 0, 0))
{
     MessageBox.Show("You need to feed the dog now");
}

如果您只使用小时作为限制,您还可以:

int thisHour = DateTime.Now.Hour;
if(thisHour.CompareTo(13 - 1) + thisHour.CompareTo(16) == 0)
{
    MessageBox.Show("You need to feed the dog now.");
}

或者,对于您的扩展任务:

int thisHour = DateTime.Now.Hour;
string salutation = "Good Evening";
if(thisHour < 12)
{
    salutation = "Good Morning";
}
else if (thisHour < 17)
{
    salutation = "Good Afternoon";
}
synthesizer.SpeakAsync(salutation);