Last active
July 8, 2019 15:55
-
-
Save drmfinlay/580e83b594fc84f9c0b2ccccd925fef2 to your computer and use it in GitHub Desktop.
Window changes test command module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Window changes test command module | |
# This should be placed in the natlink user folder. | |
import time | |
from threading import Thread, Event | |
from ctypes import windll | |
from ctypes.wintypes import DWORD, HANDLE, HWND, LONG, WINFUNCTYPE | |
import pythoncom | |
from dragonfly import Window, get_engine | |
class ObserverThread(Thread): | |
def __init__(self): | |
Thread.__init__(self) | |
self._stop_event = Event() | |
self.daemon = True | |
def stop(self): | |
self._stop_event.set() | |
def run(self): | |
WinEventProcType = WINFUNCTYPE(None, HANDLE, DWORD, HWND, LONG, | |
LONG, DWORD, DWORD) | |
last_foreground_window = [None] | |
def callback(hWinEventHook, event, hwnd, idObject, idChild, | |
dwEventThread, dwmsEventTime): | |
window = Window.get_foreground() | |
# Note: hwnd doesn't always match window.handle, even when | |
# foreground window changed (and sometimes it didn't change) | |
if window != last_foreground_window[0]: | |
print(window) | |
last_foreground_window[0] = window | |
def set_hook(win_event_proc, event_type): | |
return windll.user32.SetWinEventHook( | |
event_type, event_type, 0, win_event_proc, 0, 0, | |
0) | |
win_event_proc = WinEventProcType(callback) | |
windll.user32.SetWinEventHook.restype = HANDLE | |
[set_hook(win_event_proc, et) for et in | |
{3, 32780, }] | |
# Recognize speech, call timer functions and handle window change | |
# events in a loop. | |
while not self._stop_event.is_set(): | |
pythoncom.PumpWaitingMessages() | |
time.sleep(0.01) | |
observer_thread = ObserverThread() | |
observer_thread.start() | |
def timer_func(): | |
observer_thread.join(0.001) | |
timer = get_engine().create_timer(timer_func, 0.05) | |
def unload(): | |
if observer_thread.is_alive(): | |
observer_thread.stop() | |
observer_thread.join(5) | |
timer.stop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment