MessageBox 没有出现 C#

MessageBox doesn't appear C#

我是 C# 的新手,所以我需要你的帮助。在我的程序中,我想发出一些警报。所以在我的应用程序中,我想在(例如)还剩一分钟时出现 MessageBox,但它没有出现。我尝试将 DateTime 变量 1 用于未来(即将到来的)时间,所以我将 2019/7/12 0:29:0 AM 和一个用于当前时间,然后我将它们都比较到 if 语句中,如果当前时间是 2019 /7/12 0:28:0 MessageBox 应该出现(见下面的代码)。但是没用。

提前致谢。

这是我的代码:

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

试试这个,我修改了你的代码以使用计时器控件。还没有编译这个,但它应该足够接近开始工作了。

 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 
     }
 }