I once again already have some working Python code to detect the insertion/removal of specific USB device types in Windows 10 (from here).
import wmi
device_connected_wql = "SELECT * FROM __InstanceCreationEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Keyboard\'"
device_disconnected_wql = "SELECT * FROM __InstanceDeletionEvent WITHIN 2 WHERE TargetInstance ISA \'Win32_Keyboard\'"
c = wmi.WMI()
connected_watcher = c.watch_for(raw_wql=device_connected_wql)
disconnected_watcher = c.watch_for(raw_wql=device_disconnected_wql)
while 1:
try:
connected = connected_watcher(timeout_ms=10)
except wmi.x_wmi_timed_out:
pass
else:
if connected:
print("Keyboard connected")
try:
disconnected = disconnected_watcher(timeout_ms=10)
except wmi.x_wmi_timed_out:
pass
else:
if disconnected:
print("Keyboard disconnected")
I wanted to use this code in a Python script that runs on Windows 10 in VirtualBox 6.0.22 on Ubuntu 18.04 (x64). VirtualBox Guest Additions are installed.
Unfortunately this script does not work, because it does not display any message when a USB keyboard is inserted or removed. Does the VirtualBox configuration need to be changed for this?
However, the following error appears when exiting the script:
Process finished with exit code -1