Skip to content

Instantly share code, notes, and snippets.

@jay
Last active June 17, 2026 15:22
Show Gist options
  • Select an option

  • Save jay/09d422a019b778fa63bf8fab75aafd26 to your computer and use it in GitHub Desktop.

Select an option

Save jay/09d422a019b778fa63bf8fab75aafd26 to your computer and use it in GitHub Desktop.
Monitor for last input time change in Windows.
/* Monitor for last input time change in Windows.
Usage: lastinput
g++ -o lastinput lastinput.cpp
* Copyright (C) 2026 Jay Satiro <raysatiro@yahoo.com>
https://gist.github.com/jay/09d422a019b778fa63bf8fab75aafd26
*/
#define _WIN32_WINNT 0x0501
#include <windows.h>
#include <stdio.h>
#include <time.h>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
/* system time in format: Tue May 16 03:24:31.123 PM */
string SystemTimeStr(const SYSTEMTIME *t)
{
const char *dow[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
const char *mon[] = { NULL, "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
stringstream ss;
unsigned t_12hr = (t->wHour > 12 ? t->wHour - 12 : t->wHour ? t->wHour : 12);
const char *t_ampm = (t->wHour < 12 ? "AM" : "PM");
ss.fill('0');
ss << dow[t->wDayOfWeek] << " "
<< mon[t->wMonth] << " "
<< setw(2) << t->wDay << " "
<< setw(2) << t_12hr << ":"
<< setw(2) << t->wMinute << ":"
<< setw(2) << t->wSecond
// << "." << setw(3) << t->wMilliseconds
<< " "
<< t_ampm;
return ss.str();
}
string now()
{
SYSTEMTIME st;
GetLocalTime(&st);
return SystemTimeStr(&st);
}
/* The timestamp style in default mode: [Sun May 28 07:00:27.999 PM]: text */
#define TIMESTAMP \
"[" << now() << "]: "
int main(int argc, char *argv[])
{
LASTINPUTINFO li = { sizeof(LASTINPUTINFO), };
DWORD prev_time_ms;
cout << "Monitoring for last input time change..." << endl;
if(GetLastInputInfo(&li)) {
prev_time_ms = li.dwTime;
}
else {
cerr << "GetLastInputInfo failed." << endl;
return 1;
}
for(;;) {
Sleep(1000);
if(GetLastInputInfo(&li)) {
if(li.dwTime != prev_time_ms) {
DWORD diff = li.dwTime - prev_time_ms;
DWORD seconds = diff / 1000;
if(diff >= 1000) {
cout << TIMESTAMP << "Input detected. "
<< "Last input was " << seconds
<< " second" << ((seconds > 1) ? "s" : "") << " ago."
<< endl;
}
prev_time_ms = li.dwTime;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment