import time import wmi from monitorcontrol import get_monitors # MSI G32CQ4 E2 input codes HDMI1 = 0x11 DISPLAYPORT = 0x0F # The USB name of your keyboard (SteelSeries Apex 5) KEYBOARD_NAME = "SteelSeries Apex 5" def set_input(source_code): monitors = get_monitors() if not monitors: print("No monitors detected.") return with monitors[0] as m: m.set_input_source(source_code) def keyboard_connected(wmi_connection): """Return True if SteelSeries Apex 5 is currently connected.""" # Query only devices matching our keyboard name (much faster) query = f"SELECT Name FROM Win32_PnPEntity WHERE Name LIKE '%{KEYBOARD_NAME}%'" devices = wmi_connection.query(query) return len(devices) > 0 def main(): print("Monitoring SteelSeries Apex 5 USB connection...") # Create WMI connection ONCE (reuse it) w = wmi.WMI() watcher = w.Win32_DeviceChangeEvent.watch_for() last_state = None while True: try: # watcher() blocks until a device event occurs event = watcher() # Check keyboard state (using the same WMI connection) connected = keyboard_connected(w) if connected != last_state: last_state = connected if connected: print("Keyboard plugged in → Switching to DisplayPort") set_input(DISPLAYPORT) else: print("Keyboard unplugged → Switching to HDMI1") set_input(HDMI1) except Exception as e: print("Error:", e) time.sleep(1) if __name__ == "__main__": main()