views:

1576

answers:

4

Is there any Win32 API to know if the computer is idle or not?

+4  A: 

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; 

  }
Sam Saffron
+1, Yep. This is the same method that I've used before. It can be P/Invoked from C# or another .NET language.
Nicholas Piasecki
+4  A: 

You can use Performance Counters to read statistics, for example the CPU utilization, disk, network, and other activities.

ChrisW
+3  A: 
1800 INFORMATION
I think it would be cool if SO's wmd editor supported Latex for equations
Simucal
I looked it up, and it was requested but denied already.
Simucal
+6  A: 

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

Roy
Great answer! +1
mafutrct