使用DeviceManager获取设备信息时遇致命运行时错误求助
问题分析与解决
核心代码问题
你的代码中循环条件i <= deviceManager.DeviceInfos.Count存在数组越界问题,这是触发致命运行时错误(错误代码0xc0000005,内存访问违规)的直接原因:
DeviceInfos.Count返回的是设备总数,而集合索引从0开始,最后一个元素的索引为Count - 1- 当
i等于Count时,访问deviceManager.DeviceInfos[i]会超出集合范围,破坏内存堆栈,引发致命错误
修正后的代码:
// Create a DeviceManager instance var deviceManager = new DeviceManager(); // Loop through the list of devices and add the name to the listbox for (int i = 0; i < deviceManager.DeviceInfos.Count; i++) { // Add the device only if it's a scanner if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType) { continue; } // Add the Scanner device to the listbox (the entire DeviceInfos object) listBox1.Items.Add(new Scanner(deviceManager.DeviceInfos[i])); }
WIA服务配置建议
之前修改服务登录设置无效,是因为核心问题不在服务配置,但可以按以下步骤恢复默认配置避免额外干扰:
- 打开服务管理器,找到Windows Image Acquisition (WIA)
- 将登录账户设为Local Service(系统默认配置),无需勾选「允许服务与桌面交互」
- 重启WIA服务,确保服务处于「正在运行」状态
额外排查方向
- 确认项目引用的WIA互操作组件与系统版本兼容(优先使用系统自带的WIA COM组件)
- 尝试以管理员权限启动程序,确保设备访问权限充足
内容的提问来源于stack exchange,提问作者Hovi906
相关产品推荐
相关产品推荐

