我是C#的新手,所以我需要您的帮助。在我的程序中,我想发出一些警报。因此,在我的应用程序中,我想在(例如)还剩一分钟时显示MessageBox,但没有出现。我试图将DateTime变量一个用于未来(即将来临)的时间,所以我将使用2019/7/12 0:29:0 AM,一个用于当前时间,然后如果当前时间是2019,则将它们都比较为if语句/ 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");
}
}
答案 0 :(得分:1)
尝试一下,我修改了您的代码以使用计时器控件。还没有编译,但是应该足够接近才能开始工作。
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
}
}