How to looping with timer?


  •  Dear all,

    I am a student making a MS Form application in C++. I would ask a question about  "Timer". Sample code which I am developing is below.

            private: System::Void buttonStart_Click(System::Object^  sender, System::EventArgs^  e){
                    for (int i=1; i<=10; i++){
                            String^ strValue;
                            int interval=1000;           // time interval of looping equal to 1s                                
                            SetTimer(timer1, interval, NULL);     
                            do {
                                               this->textBox->Text = strValue;
                            while(TimerFlag = 0);
                            TimerFlag = 0;

            private: System::Void FunctionName(String^ *strValue){
                    *strValue = "Something which could change in each time of above looping";

            private: System::Void OnTimer(int timerId){
                    if(timerId = 1){
                        TimerFlag = 1;
                         HWND hwnd = NULL;

    Compiling errors are
    1. SetTimer doesn't take 3 arguments
    2. Kill timer doesn't take 1 arguments

    How should I input the arguments and how should I correctly looping with 1s interruption? Please help me! 

    Thank you very much in advance.


    Wednesday, July 09, 2008 11:21 AM


  • You can't use the native SetTimer() function, use a System::Windows::Forms::Timer instead.  You also can't use a loop inside the Click event handler, it prevents windows messages from getting dispatched.  Do it like this:

        int mTimerTick;
        System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
          mTimerTick = 0;
          timer1->Enabled = true;
        System::Void timer1_Tick(System::Object^  sender, System::EventArgs^  e) {
          if (++mTimerTick >= 10) timer1->Enabled = false;
          else {
            // Do something

    Hans Passant.
    • Marked as answer by Yan-Fei Wei Tuesday, July 15, 2008 6:21 AM
    Wednesday, July 09, 2008 12:10 PM