windows – Making a countdown timer in C++

windows – Making a countdown timer in C++

//Please note that this is Windows specific code
#include <iostream>
#include <Windows.h>
using namespace std;

int main()
{
    int counter = 60; //amount of seconds
    Sleep(1000);
    while (counter >= 1)
    {
        cout << rTime remaining:  << counter << flush;
        Sleep(1000);
        counter--;
    }
}

You can use sleep() system call to sleep for 60 seconds.

You can follow this link for how to set 60 seconds timer using system call Timer in C++ using system calls.

windows – Making a countdown timer in C++

possible use Waitable Timer Objects with perion set to 1 second for this task. possible implementation

VOID CALLBACK TimerAPCProc(
                           __in_opt  LPVOID /*lpArgToCompletionRoutine*/,
                           __in      DWORD /*dwTimerLowValue*/,
                           __in      DWORD /*dwTimerHighValue*/
                           )
{
}

void CountDown(ULONG Seconds, COORD dwCursorPosition)
{
    if (HANDLE hTimer = CreateWaitableTimer(0, 0, 0))
    {
        static LARGE_INTEGER DueTime = { (ULONG)-1, -1};//just now
        ULONGLONG _t = GetTickCount64() + Seconds*1000, t;
        if (SetWaitableTimer(hTimer, &DueTime, 1000, TimerAPCProc, 0, FALSE))
        {
            HANDLE hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE);
            do 
            {
                SleepEx(INFINITE, TRUE);
                t = GetTickCount64();
                if (t >= _t)
                {
                    break;
                }
                if (SetConsoleCursorPosition(hConsoleOutput, dwCursorPosition))
                {
                    WCHAR sz[8];
                    WriteConsoleW(hConsoleOutput, 
                        sz, swprintf(sz, L%02u.., (ULONG)((_t - t)/1000)), 0, 0);
                }
            } while (TRUE);
        }
        CloseHandle(hTimer);
    }
}
    COORD dwCursorPosition = { };
    CountDown(60, dwCursorPosition);

Leave a Reply

Your email address will not be published.