The other day, I received a request to create a script that could tell how long a Windows XP machine had been idle and to alert the user if it had been idle for a certain amount of time. I did a little research with Google and found a couple of ways to accomplish this feat. The only one I was able to get working was a ctypes example, so without further ado, let’s check it out!
The following ctypes-related code was taken from a stackoverflow forum:
from ctypes import Structure, windll, c_uint, sizeof, byref # http://stackoverflow.com/questions/911856/detecting-idle-time-in-python class LASTINPUTINFO(Structure): _fields_ = [ ('cbSize', c_uint), ('dwTime', c_uint), ] def get_idle_duration(): lastInputInfo = LASTINPUTINFO() lastInputInfo.cbSize = sizeof(lastInputInfo) windll.user32.GetLastInputInfo(byref(lastInputInfo)) millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime return millis / 1000.0
If you don’t understand the code above, please ask for help on the ctypes mailing list. I don’t really understand it all either. I get the basic gist, but that’s it. Here’s the snippet I use to make the code above do its thing:
while 1: GetLastInputInfo = int(get_idle_duration()) print GetLastInputInfo if GetLastInputInfo == 480: # if GetLastInputInfo is 8 minutes, play a sound sound = r"c:\windows\media\notify.wav" winsound.PlaySound(sound, winsound.SND_FILENAME) if GetLastInputInfo == 560: # if GetLastInputInfo is 9 minutes, play a more annoying sound sound = r"c:\windows\media\ringout.wav" winsound.PlaySound(sound, winsound.SND_FILENAME) winsound.PlaySound(sound, winsound.SND_FILENAME) winsound.PlaySound(sound, winsound.SND_FILENAME) time.sleep(1)
In my code, I check if the machine has been idle for 8 minutes and 9 minutes. Depending on how long it’s been idle, the code plays a specific wav file with Python winsound module. In our shop, we have certain machines lock themselves if they’ve been idle for 10 minutes. Our users don’t like that too much, so they requested that we warn them with a sound when the machine was about to lock. That is what this script accomplishes. Hopefully you can find a better use for this knowledge.