user124626
user124626

Reputation:

wxPython - Trapping Mouse & Keyboard Events without window Focus

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 :)

Upvotes: 1

Views: 1469

Answers (1)

FogleBird
FogleBird

Reputation: 76822

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

Upvotes: 3

Related Questions