none
Timer can not be used as a clock. c++/CLI VS2008 RRS feed

  • 问题

  • int k;
    int x;
    private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
      x=0;
      GetLocalTime(&time);
      int min=Int32::Parse(time.wMinute.ToString() );
      int sec=Int32::Parse(time.wSecond.ToString() );
      int mil=Int32::Parse(time.wMilliseconds.ToString()  );
      k =min*60*1000+sec*1000+mil;                             //current time
      this->timer1 ->Interval = 1000;
      this->timer1 ->Enabled =true;                                //start Timer
       }
       
    private: System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
       x=x+1;                
       if(x>10){      //after the tick be called 10 time, calculate the elapsed time
          this->timer1 ->Enabled =false;
       GetLocalTime(&time);
       int min=Int32::Parse(time.wMinute.ToString() );
       int sec=Int32::Parse(time.wSecond.ToString() );
       int mil=Int32::Parse(time.wMilliseconds.ToString()  );
       k =(min*60*1000+sec*1000+mil-k)/10;                            //     total elapsed time/10
       this->textBox1 ->Text +=k.ToString ()+"\r\n";                  //     output the result
       }
      }
    After I clicked the button1, the Tick(timer1) will be called 10 times.
    What will be the value of the variable "k"? You may say it is 1000.
    When you see the result in the textBox, you will find you are wrong.
    The value is 1100.

    I am writing a piano, and need starting the sounds at the appointed time.
    I use the Timer as a clock. After the Tick is called 50 times,
    I find the sounds are delayed for several hundred milliseconds

    I need starting the sounds at the appointed time, can you help me?

    2012年7月28日 22:01

答案

  • 为什么button1的click事件代码和timer1的tick事件代码那么相近?

    你真的要在这两个事件中实现相似的功能吗?

    tick只有在timer1被start的时候,才会执行。从代码中没有看到执行十次的功能。

    在click事件中,第一行代码就是x=0;,而且也没有timer的start函数,不知道timer什么时候会触发。

    如果是要在click事件中触发,你应该在最后添加timer1.start();

    既然你想在预约时间发出声音,为什么不获取当前时间,然后和预约时间进行比较呢?

    我不认为timer有做clock的功能。

    我建议你获取当前时间,然后和预约时间进行比较,如果时间到了,就发出声音。

    你可以在click时间中设置timer并调用start函数。

    在timer时间中获取时间并加以比较。


    Please mark this reply as answer if it helps you! Thanks for your cooperation! Good Luck to you.

    2012年7月30日 5:54