如何在条件的间隔中显示MessageBox

时间:2016-05-08 15:41:09

标签: c# winforms if-statement timer

如果在C#中正好是下午5点,我怎么能调用MessageBox.Show命令?

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    const double interval60Minutes = 1000; // milliseconds to one hour
    System.Timers.Timer checkForTime = new System.Timers.Timer(interval60Minutes);

    string Check = null;
    private void Form1_Load(object sender, EventArgs e)
    {
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;
    }


    public void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {

        DateTime target = new DateTime(2016, 5, 8, 11, 58, 0);
        DateTime now = DateTime.Now;

        if (target.ToString("HH:mm:ss") == now.ToString("HH:mm:ss") && (Check == null))
        {
            MessageBox.Show("Welcome Admin");
            checkForTime.Stop();
            checkForTime.Enabled = false;
        }
    }
}

如果我只使用MessageBox.Show而没有if语句就可以了,但是当我提出条件时没有任何反应。计时器不会停止我同时使用enabled = false和停止功能。

1 个答案:

答案 0 :(得分:0)

使用此代码,此代码将检查您的目标时间和当前时间是否相同,然后它将运行MessageBox

if (target.ToString("HH:mm:ss") == now.ToString("HH:mm:ss"))
   {
       MessageBox.Show("It's Time");
   }

使用

checkForTime.Stop();

你想要停止计时器

从另一种方法访问计时器,将计时器放在全局范围内

    const double interval60Minutes = 1000; // milliseconds to one hour
    System.Timers.Timer checkForTime = new System.Timers.Timer(interval60Minutes);

    string Check = null;
    private void Form1_Load(object sender, EventArgs e)
    {
        checkForTime.Elapsed += new ElapsedEventHandler(checkForTime_Elapsed);
        checkForTime.Enabled = true;
        checkForTime.AutoReset = false;
    }


    public void checkForTime_Elapsed(object sender, ElapsedEventArgs e)
    {

        DateTime target = new DateTime(2016, 5, 8, 11, 58, 0);
        DateTime now = DateTime.Now;

        if (target.ToString("HH:mm:ss") == now.ToString("HH:mm:ss") && (Check == null))
        {
            MessageBox.Show("Welcome Admin");
            checkForTime.Stop();
        }

    }