在 C 中制作倒数计时器

新手上路,请多包涵

我有一个 只能在 windows 上运行 的控制台应用程序。它是用 C++ 编写的。有什么方法可以等待 60 秒(并在屏幕上 显示剩余时间)然后继续代码流?

我尝试了互联网上的不同解决方案,但没有一个有效。它们要么不工作,要么不能正确显示时间。

原文由 H4ZE 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 674
2 个回答
//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--;
    }
}

原文由 H4ZE 发布,翻译遵循 CC BY-SA 4.0 许可协议

对于此任务,可能使用将 perion 设置为 1 秒的可等待 计时器对象。可能的实施

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);

原文由 RbMm 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题