views:

606

answers:

1

I am attempting to write a time management tool with wxPython that is ideally non-obtrusive and very much out of the way. The app so far can be used normally and minimized to the system tray for the duration of its use.

However, I notice that once the frame is not in focus, as it is when its 'Iconized', the mouse and keyboard trapping that normally works when the frame/app is in focus no longer works.

I am aware that I could write a C++ program to create a Message Queue Hook and trap all mouse and keyboard events at the OS level, but Id rather not roll up my sleeves that far. After all trying to avoid getting my hands that dirty is why I am writing the UI in wxPython in the first place :)

+2  A: 

Do you really need mouse and keyboard events or would it be sufficient to just know if the user has been idle? (You mentioned a time management app, so this seems feasible.)

This code will work on Windows and returns the idle time in seconds.

from ctypes import Structure, windll, c_uint, sizeof, byref

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
FogleBird
Holy Cow. Yes I suppose you're right (faceplant).There was a fantasy about breaking down the user's keyboard time and mouse time but I suppose that might be one of those really really really after-thought and needless type things.Thank you for this.
Matt1776
Also .. is this how you combine C and python? Is it this easy?
Matt1776
ctypes and pywin32 provide access to Windows APIs. You can also integrate your own C code into a Python app, but that's different.
FogleBird