Is there any Win32 API to know if the computer is idle or not?
Assuming that by idle you mean the keyboard and mouse are not in use. You could use GetLastInputInfo
In Vista this will not work properly from a service (you need to launch a process as a user). In terminal service environments getting this to work may be a little tricky.
int _tmain(int argc, _TCHAR* argv[])
{
DWORD previous = 0;
while(true)
{
LASTINPUTINFO info;
info.cbSize = sizeof(info);
GetLastInputInfo(&info);
DWORD idleSeconds = (GetTickCount() - info.dwTime)/1000;
if (idleSeconds < previous)
{
printf("Idle time: %i\n",previous);
}
Sleep(1000);
previous = idleSeconds;
}
You can use Performance Counters to read statistics, for example the CPU utilization, disk, network, and other activities.
Unfortunately, the definition of "idle" for a computer is very vague. For example, Win32 screensavers determine that a computer is idle if there is no keyboard or mouse input for N minutes whether or not the CPU has a high load. And there are several other valid measures of what constitutes an "idle" machine. Here are my top three measures and related techniques:
(1) Wait for keyboard/mouse to be idle x N mins
* a very reasonable implementation has been given here by @sambo99
(2) Use performance counters to determine CPU usage (or disk, ...)
* again, several good references are posted in this thread by @ChrisW and @1800 INFORMATION
(3) Execute your code on a thread with IDLE priority
* by definition, Win32 will only execute your code when the machine is idle