C# WinForm中MessageBox的持续弹出问题

4
这是我的代码:
private void btnReminder_Click(object sender, EventArgs e)
{
    timer2.Start();
}

private void timer2_Tick(object sender, EventArgs e)
{
    DateTime Date = DateTimePickerReminderDate.Value;
    DateTime Time = DateTimePickerReminderTime.Value;
    if (DateTime.Now.CompareTo(Date) > 0 && DateTime.Now.CompareTo(Time) > 0) 
    {
        Date = DateTime.MaxValue;
        Time = DateTime.MaxValue; 
        MessageBox.Show("Your Reminder");

        timer2.Stop();     
    }
}   

当我设置提醒时,它按预期工作并在正确的时间显示消息。但是问题是,它不断弹出消息框。我尝试清除这个错误,但是没有成功。所以现在我需要专家的建议,请帮助我解决这个错误。
1个回答

12

MessageBox会在显示时阻塞您的UI线程,因此在您点击对话框之前,不会达到timer.Stop()。 请在显示MessageBox之前尝试先停止计时器:

private void timer2_Tick(object sender, EventArgs e)
{
    DateTime Date = DateTimePickerReminderDate.Value;
    DateTime Time = DateTimePickerReminderTime.Value;
    if (DateTime.Now.CompareTo(Date) > 0 && DateTime.Now.CompareTo(Time) > 0) 
    {
        timer2.Stop();     

        Date = DateTime.MaxValue;
        Time = DateTime.MaxValue; 
        MessageBox.Show("Your Reminder");
    }
}  

4
如果某个答案解决了你的问题,你应该接受它,这样其他人就会知道问题已经解决了。 - Zohar Peled
@Zohar Peled,谢谢您,在我的上一条评论中我已经接受了这个建议。如果有其他方法,请告诉我,我一定会尝试的 :) - Rock
1
@Rock:在答案分数下面有一个V标记,您应该点击它。这将把答案标记为已接受,这样当其他人查看问题列表时,答案数量会变成黄色而不是白色。这还会给回答问题的用户15个声望点,以及给提问者2个声望点。 - Zohar Peled
1
@Zohar Pared 我记住了你的建议,从现在开始我一定会遵循它 :) - Rock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接