Search code examples
c++winapitimer

Timer time-out reset


I use a timer to draw animations, but I want the speed of the animation to change upon user input.

On the API's documentation, I read:

A handle to the window to be associated with the timer. This window must be owned by the calling thread. If a NULL value for hWnd is passed in along with an nIDEvent of an existing timer, that timer will be replaced in the same way that an existing non-NULL hWnd timer will be.

I understood that I am supposed to call the SetTimer() function without the hWnd parameter to reset the timer, and so I did:

//function declaration

void InitiateTimer(HWND hWnd)
{
    SetTimer(hWnd,                          // handle to main window 
        IDT_TIMER,                          // timer identifier 
        1000 / Robot_Settings::getSpeed(),  // 1-second interval / speed 
        (TIMERPROC)NULL);                   // no timer callback 

    timerInitiated = true;
}

void ResetTimer()
{
    SetTimer(NULL,
        IDT_TIMER, 
        1000 / Robot_Settings::getSpeed(), 
        (TIMERPROC)NULL);
}

//function call in WindowProc

    case BUTTON_START:
        stopClicked = false;
        DestroyWindow(hStartButton);
        CreateStopButton(hWnd);
        if (!timerInitiated)
        {
            InitiateTimer(hWnd);
        }
        else if (timerInitiated)
        {
            ResetTimer();
        }
        return 0;

The idea was that on the reset, the timeout would be recalculated based on Robot_Settings::getSpeed(). Unfortunately, this doesn't happen.

What did I miss?


Solution

  • I think you have misunderstood the docs.

    To change an existing timer, you have to pass the same combination of hWnd, nIDEvent and lpTimerFunc arguments as when you initially called SetTimer.

    From the reference:

    If the hWnd parameter is not NULL and the window specified by hWnd already has a timer with the value nIDEvent, then the existing timer is replaced by the new timer.

    Also:

    The timer identifier, nIDEvent, is specific to the associated window. Another window can have its own timer which has the same identifier as a timer owned by another window. The timers are distinct.

    The last quote alone is proof enough that you always have to specify the hWnd parameter to modify an existing timer that is associated with a window. Otherwise, how should the system know, which timer do you want to change? You could have two windows, each with a timer ID of 1, which are two distinct timers!