使用Python获取Windows触摸屏设备驱动状态属性
监控Windows触摸屏设备驱动状态的Python实现方案
要获取触摸屏设备的is connected、is present、needs restart、has problem这几个状态,最可靠的方式是通过Windows Management Instrumentation (WMI) 访问系统设备信息——WMI直接对接设备管理器的底层数据,比注册表或普通win32api更精准。
实现步骤
- 安装依赖库:使用
wmi库简化WMI调用,执行以下命令安装:
pip install wmi
- 编写监控脚本:
import wmi def check_touch_device_status(): # 连接本地WMI服务 wmi_client = wmi.WMI() # 筛选触摸屏设备(可根据实际设备名称调整匹配规则) touch_devices = wmi_client.Win32_PnPEntity(Name__like="%Touch%") if not touch_devices: print("未检测到触摸屏设备") return for device in touch_devices: print(f"设备名称: {device.Name}") # 判断设备是否存在 is_present = bool(device.Present) print(f"is present: {is_present}") # 判断设备是否已连接:结合运行状态(Availability=5)和状态码 is_connected = False if hasattr(device, "Availability") and device.Availability == 5: is_connected = True elif device.Status == "OK": is_connected = True print(f"is connected: {is_connected}") # 判断是否需要重启:ConfigManagerErrorCode=1表示需重启 needs_restart = False if hasattr(device, "ConfigManagerErrorCode") and device.ConfigManagerErrorCode == 1: needs_restart = True print(f"needs restart: {needs_restart}") # 判断是否存在问题:状态非OK或配置错误码不为0 has_problem = device.Status != "OK" or (hasattr(device, "ConfigManagerErrorCode") and device.ConfigManagerErrorCode != 0) print(f"has problem: {has_problem}") print("-" * 50) if __name__ == "__main__": check_touch_device_status()
备选方案(使用pywin32)
如果不想额外安装wmi库,也可以用pywin32自带的COM接口调用WMI:
import win32com.client def check_touch_status_win32(): wmi_service = win32com.client.GetObject("winmgmts:") all_devices = wmi_service.InstancesOf("Win32_PnPEntity") for device in all_devices: device_name = device.Name # 匹配触摸屏设备 if "Touch" in device_name or "触摸屏" in device_name: print(f"设备名称: {device_name}") is_present = bool(device.Present) print(f"is present: {is_present}") is_connected = False if hasattr(device, "Availability") and device.Availability == 5: is_connected = True elif device.Status == "OK": is_connected = True print(f"is connected: {is_connected}") needs_restart = hasattr(device, "ConfigManagerErrorCode") and device.ConfigManagerErrorCode == 1 print(f"needs restart: {needs_restart}") has_problem = device.Status != "OK" or (hasattr(device, "ConfigManagerErrorCode") and device.ConfigManagerErrorCode != 0) print(f"has problem: {has_problem}") print("-" * 50) if __name__ == "__main__": check_touch_status_win32()
注意事项
- 脚本需要以管理员权限运行,否则可能无法读取完整的设备配置信息
- 设备名称匹配规则可根据实际硬件调整:比如部分中文设备显示为“触摸屏”,可修改
Name__like为"%触摸屏%",或通过硬件ID(DeviceID__like="%HID%")筛选更精准 - 部分旧设备可能缺少
Availability属性,代码中用hasattr做了兼容判断,避免报错
内容的提问来源于stack exchange,提问作者user21959877
相关产品推荐
相关产品推荐

