Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

winforms - Timer firing every second and updating GUI (C# Windows Forms)

I have a Windows Forms application where I need to have a timer working for 90 seconds and every second should be shown after it elapses, kind of like a stopwatch 1..2..3 etc, after 90 seconds is up, it should throw an exception that something is wrong.

I have the following code, but the RunEvent never fires.

        private void ScanpXRF()
        {
            bool demo = false;

            System.Windows.Forms.Timer timer = new System.Windows.Forms.Timer();

            try
            {

                for (int timerCounter = 0; timerCounter < 90; timerCounter++)
                {
                    timer.Interval = 1000;
                    timer.Tick += new EventHandler(RunEvent);
                    timer.Start();

                    if(timerCounter == 89) {
                      throw new Exception(); 
                     }
                }

            }
            catch (Exception e)
            {
                timer.Dispose();
                MessageBox.Show("There is a problem!");                   
            }       
        }


          private void RunEvent(object sender, System.EventArgs e)
            {
                //boxStatus.AppendText("RunEvent() called at " + DateTime.Now.ToLongTimeString() + "
");
                MessageBox.Show("timer fired!");
            }

Is there anything I am doing wrong here or are there other suggestions for other ways to achieve the same result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A timer needs to be declared at the form level, or else it may not be disposed of when the form closes:

System.Windows.Forms.Timer timer;
int counter = 0;

Your starting code should just start the timer:

private void ScanpXRF()
{
   counter = 0;
   timer = new System.Windows.Forms.Timer();
   timer.Interval = 1000;
   timer.Tick += RunEvent;
   timer.Start();
}

The RunEvent is your Tick event being called every second, so your logic needs to go in there:

private void RunEvent(object sender, EventArgs e)
{
  counter++;
  if (counter >= 90) {
    timer.Stop();
    // do something...
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...