MessageBox continuous popup in C # WinForm

This is my code:

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();     
    }
}   

When I set a reminder, it works as expected and displays the message at the right time. But the problem is that it constantly gives a popup with a message. I tried to clear this error, but I was unsuccessful. Right now you need expert advice, so please help me fix this error.

WIRPS.jpg

+4
source share
1 answer

MessageBoxwill block your UI thread during display, and you will not reach timer.Stop()before clicking the dialog. Try to stop the timer until you show your 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");
    }
}  
+12
source

Source: https://habr.com/ru/post/1628703/


All Articles