Search code examples
c#datetimealertmessagebox

MessageBox doesn't appear C#


I'm new in C# so i need your help. In my program i want to make some alert. So in my application i want to appear MessageBox when (for example) one minute is left, but it doesn't appear. I tried to use DateTime variable one for future(upcoming) time, so i take 2019/7/12 0:29:0 AM, and one for current time, then i compare both of them into if statement, if current time is 2019/7/12 0:28:0 MessageBox Should be appeared(see code below). But it doesn't work.

Thank you in advance.

Here is my code:

 public Form1()
 {
     InitializeComponent();
     TimeCounter();
 }

 public void TimeCounter()
 {
     DateTime dt1 = new DateTime(2019, 7, 12, 0, 29, 0);
     DateTime dt2 = DateTime.Now;

     if (dt2.Minute == dt1.Minute - 1)
     {
          MessageBox.Show("1 Minute left");
     }
 }

Solution

  • Try this, I modified your code to use the timer control. Haven't compiled this but it should be close enough to get working.

     public Form1()
     {
         InitializeComponent();
    
         timer = new Timer();
         timer.Interval = 1000; // this is every second
         timer.Enabled = true;
         timer.Tick += timer_Tick;  // Ties the function below to the Tick event of the timer
         timer.Start(); // starts the timer, it will fire its tick even every interval
     }
    
     // these needs to go here so they are in class scope
     Timer timer; 
     DateTime dt1 = new DateTime(2019, 7, 12, 0, 29, 0);
    
     public void timer_Tick(object sender, EventArgs e)
     { 
         if (dt1.AddMinutes(-1) > DateTime.Now)
         {
              MessageBox.Show("1 Minute left");
              timer.Stop();  // stop the timer so you dont see the same message box every second 
         }
     }