我想在特定时间执行活动
我添加了一个800毫秒的计时器,并在计时器事件中我比较了设定值和当前时间 但问题是事件发生的时间超过了时间,因为它显示在照片中,因为消息箱必须发生一次代码,但是当我执行它时会发生7次或更多次 代码是:
private void timer2_Tick(object sender, EventArgs e)
{
DateTime date1 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, Convert.ToInt16(Properties.Settings.Default.shift_1_end_hh), Convert.ToInt16(Properties.Settings.Default.shift_1_end_min), 0);
DateTime date2 = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour, DateTime.Now.Minute, DateTime.Now.Second);
int result = DateTime.Compare(date1, date2);
if (result == 0)
{
MessageBox.Show("tttt");
}
}
答案 0 :(得分:1)
以下是您的代码的更好版本:
private void timer2_Tick(object sender, EventArgs e)
{
var hours = Convert.ToInt16(Properties.Settings.Default.shift_1_end_hh);
var minutes = Convert.ToInt16(Properties.Settings.Default.shift_1_end_min);
var date1 = DateTime.Today.AddHours(hours).AddMinutes(minutes);
int result = DateTime.Compare(date1,DateTime.Now);
if (result == 0)
{
timer2.Enabled = false;
MessageBox.Show("tttt");
}
}
兴趣点:
date1
date2
,只需使用DateTime.Now
代替答案 1 :(得分:0)
您可以在这里找到更好的解决方案[How to compare dates in c#
答案 2 :(得分:0)
试试这个
if (result == 0)
{
if (timer2.IsEnabled)
{
timer2.Stop();
}
MessageBox.Show("tttt");
}