C#WinForm中MessageBox的连续弹出

时间:2016-02-14 11:29:15

标签: c# winforms messagebox

这是我的代码:

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 个答案:

答案 0 :(得分: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");
    }
}