c++ – Measuring time after entering a character

Question:

I am writing a program that receives text as input. If I do not write anything, then after n seconds a message about my inactivity will appear on the screen. How can you implement such a timer that will turn on after each letter is entered?

Answer:

#pragma warning(disable: 4996)

#include <Windows.h>
#include <iostream>
#include <string>
#include <ctime>

using namespace std;

const int how_many_seconds_should_go = 2;//Интервал проверки 2 секунды

bool bTimerSec(time_t start_time, const int& how_many_seconds_should_go)
{
    return time(0) == start_time + abs(how_many_seconds_should_go);
}

void checkThread(LPVOID param) 
{
    bool bFlag = false;
    int time_;

    while (true)
    {
        if (!bFlag)
        {
            time_ = time(0);
            bFlag = true;
        }
        else
        {
            if (bTimerSec(time_, how_many_seconds_should_go))
            {
                MessageBox(0, "Вы бездействуете!", "", 0);
                return;
            }
        }

        Sleep(1);
    }
}

int main() {

    string s;
    HANDLE hThread = 0;

    while (cin >> s)
    {
        if (hThread)
        {
            TerminateThread(hThread, 0);
        }

        hThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)checkThread, 0, 0, 0);

    }

    while (true)
    {
        Sleep(1);
    }

    return 0;
}
Scroll to Top