123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107 |
-
-
-
- import sys
- import time
-
- import win32api
- import win32con
- import win32file
- import win32gui
- import win32gui_struct
- import winnt
-
-
-
- GUID_DEVINTERFACE_USB_DEVICE = "{A5DCBF10-6530-11D2-901F-00C04FB951ED}"
-
-
-
- def OnDeviceChange(hwnd, msg, wp, lp):
-
-
- info = win32gui_struct.UnpackDEV_BROADCAST(lp)
- print("Device change notification:", wp, str(info))
- if (
- wp == win32con.DBT_DEVICEQUERYREMOVE
- and info.devicetype == win32con.DBT_DEVTYP_HANDLE
- ):
-
- print("Device being removed - closing handle")
- win32file.CloseHandle(info.handle)
-
-
- win32gui.UnregisterDeviceNotification(info.hdevnotify)
- return True
-
-
- def TestDeviceNotifications(dir_names):
- wc = win32gui.WNDCLASS()
- wc.lpszClassName = "test_devicenotify"
- wc.style = win32con.CS_GLOBALCLASS | win32con.CS_VREDRAW | win32con.CS_HREDRAW
- wc.hbrBackground = win32con.COLOR_WINDOW + 1
- wc.lpfnWndProc = {win32con.WM_DEVICECHANGE: OnDeviceChange}
- class_atom = win32gui.RegisterClass(wc)
- hwnd = win32gui.CreateWindow(
- wc.lpszClassName,
- "Testing some devices",
-
- win32con.WS_CAPTION,
- 100,
- 100,
- 900,
- 900,
- 0,
- 0,
- 0,
- None,
- )
-
- hdevs = []
-
- filter = win32gui_struct.PackDEV_BROADCAST_DEVICEINTERFACE(
- GUID_DEVINTERFACE_USB_DEVICE
- )
- hdev = win32gui.RegisterDeviceNotification(
- hwnd, filter, win32con.DEVICE_NOTIFY_WINDOW_HANDLE
- )
- hdevs.append(hdev)
-
- for d in dir_names:
- hdir = win32file.CreateFile(
- d,
- winnt.FILE_LIST_DIRECTORY,
- winnt.FILE_SHARE_READ | winnt.FILE_SHARE_WRITE | winnt.FILE_SHARE_DELETE,
- None,
- win32con.OPEN_EXISTING,
- win32con.FILE_FLAG_BACKUP_SEMANTICS
- | win32con.FILE_FLAG_OVERLAPPED,
- None,
- )
-
- filter = win32gui_struct.PackDEV_BROADCAST_HANDLE(hdir)
- hdev = win32gui.RegisterDeviceNotification(
- hwnd, filter, win32con.DEVICE_NOTIFY_WINDOW_HANDLE
- )
- hdevs.append(hdev)
-
-
- print("Watching", len(hdevs), "handles - press Ctrl+C to terminate, or")
- print("add and remove some USB devices...")
- if not dir_names:
- print("(Note you can also pass paths to watch on the command-line - eg,")
- print("pass the root of an inserted USB stick to see events specific to")
- print("that volume)")
- while 1:
- win32gui.PumpWaitingMessages()
- time.sleep(0.01)
- win32gui.DestroyWindow(hwnd)
- win32gui.UnregisterClass(wc.lpszClassName, None)
-
-
- if __name__ == "__main__":
-
-
-
-
- TestDeviceNotifications(sys.argv[1:])
|