import ctypes
import threading
import time

import win32con
import win32service

h_desk = win32service.OpenDesktop("Default", 0, False, win32con.GENERIC_ALL)
ctypes.windll.user32.SetThreadDesktop(int(h_desk))
VK_F9 = 0x78

def loop():
    ctypes.windll.user32.SetThreadDesktop(int(h_desk))
    for i in range(20):
        st = ctypes.windll.user32.GetAsyncKeyState(VK_F9)
        if st & 1 or st & 0x8000:
            print(f"F9 DETECTED IN THREAD at step {i} (state={hex(st)})!")
            return
        time.sleep(0.05)
    print("F9 not detected within 20 steps.")

t = threading.Thread(target=loop)
t.start()
time.sleep(0.1)

# Press F9 on Default desktop
ctypes.windll.user32.keybd_event(VK_F9, 0, 0, 0)
time.sleep(0.02)
ctypes.windll.user32.keybd_event(VK_F9, 0, 2, 0)

t.join()
