本文介绍如何编写windows程序访问USB HID设备.
已知Windows系统不支持对于USB的直接访问(Linux 可直接发送传输命令到USB设备),必须通过设备驱动程序提供的API来访问设备。下面介绍访问的方法:
1.) 通过Windows系统提供的hid.dll函数来访问,可以得到hid信息,通过通用的API ReadFile WriteFile来进行数据读写。在打开文件句柄之前必须得文件的名字,Win32提供标准的动态链接库来支持对于设备的访问:setupapi.dll是对于所有设备驱动程序安装、枚举。 该连接有详细介绍.
如何加载setupapi.dll/hid.dll:
一种方法是从ddk下载 setupapi.lib/hid.lib 动态链接库函数表文件(注意:因为windows 库是向下兼容的,应该下载最新的表文件,例如win8),将这两个文件加入到工程中,以c为例:
#include "usb_hid/hidsdi.h"
#include
#pragma comment(lib,"setupapi.lib")
#pragma comment(lib,"setupapi.lib")
另一种方法是直接从dll 引入函数, VC++:
typedef BOOL (__stdcall SETUPDIENUMDEVICEINFO)(HDEVINFO, DWORD, PSP_DEVINFO_DATA);
typedef HDEVINFO (__stdcall SETUPDIGETCLASSDEVS)(LPGUID, LPCTSTR, HWND, DWORD);
typedef BOOL (__stdcall SETUPDIGETDEVICEREGISTRYPROPERTY)(HDEVINFO, PSP_DEVINFO_DATA, DWORD, PDWORD, PBYTE, DWORD, PDWORD);
HINSTANCE hSetupAPI = LoadLibrary(_T("SETUPAPI.DLL"));
if (hSetupAPI == NULL){
AfxMessageBox(" error to load dll ");
return;
}
SETUPDIOPENDEVREGKEY* lpfnLPSETUPDIOPENDEVREGKEY = (SETUPDIOPENDEVREGKEY*) GetProcAddress(hSetupAPI, "SetupDiOpenDevRegKey");
#ifdef _UNICODE
SETUPDIGETCLASSDEVS* lpfnSETUPDIGETCLASSDEVS = (SETUPDIGETCLASSDEVS*) GetProcAddress(hSetupAPI, "SetupDiGetClassDevsW");
#else
SETUPDIGETCLASSDEVS* lpfnSETUPDIGETCLASSDEVS = (SETUPDIGETCLASSDEVS*) GetProcAddress(hSetupAPI, "SetupDiGetClassDevsA");
#endif
SETUPDIDESTROYDEVICEINFOLIST*
lpfnSETUPDIDESTROYDEVICEINFOLIST = (SETUPDIDESTROYDEVICEINFOLIST*)
GetProcAddress(hSetupAPI, "SetupDiDestroyDeviceInfoList");
SETUPDIENUMDEVICEINFO* lpfnSETUPDIENUMDEVICEINFO = (SETUPDIENUMDEVICEINFO*) GetProcAddress(hSetupAPI, "SetupDiEnumDeviceInfo");
C# 更加简单了:
//Gives us "PSP_DEVICE_INTERFACE_DATA" which contains the Interface specific GUID (different
//from class GUID). We need the interface GUID to get the device path.
[DllImport("setupapi.dll" , CharSet = CharSet::Seeifdef, EntryPoint="SetupDiEnumDeviceInterfaces", CallingConvention=CallingConvention::Winapi)]
extern "C" WINSETUPAPI BOOL WINAPI SetupDiEnumDeviceInterfacesUM(
HDEVINFO DeviceInfoSet, //Input: Give it the HDEVINFO we got from SetupDiGetClassDevs()
PSP_DEVINFO_DATA DeviceInfoData, //Input (optional)
LPGUID InterfaceClassGuid, //Input
DWORD MemberIndex, //Input: "Index" of the device you are interested in getting the path for.
PSP_DEVICE_INTERFACE_DATA DeviceInterfaceData);//Output: This function fills in an "SP_DEVICE_INTERFACE_DATA" structure.
这两种方法都可以调用win32标准的api来实现对于USB HID 设备的访问了。
2.) 这里讲道可以通过opensource的USB库 libusb-win32 来实现对于USB 设备的直接访问。如何使用网络上有很多介绍,这里不再做详细描述。
阅读(2555) | 评论(1) | 转发(0) |