while (true) {
uint read = 0;
//注意字节的长度,我这里写的是8位,其实可以通过API获取具体的长度,这样安全点,
//具体方法我知道,但是没有写,过几天整理完代码,一起给出来 Byte[] m_rd_data = new Byte[8];
bool isread = ReadFile((IntPtr)handle, m_rd_data, (uint)8, ref read, IntPtr.Zero);
//这里已经是拿到的数据了
Byte[] m_rd_dataout = new Byte[read];
Array.Copy(m_rd_data, m_rd_dataout, read); } }
OK,如果只是获取USB传过来的数据,这里已经足够了,但是有点要注意,2000和XP如果要获取HID键盘和鼠标的数据,readfile是不行的,;
在Win2000和WinXP下不能用CreateFile+ReadFile/WriteFile的方式来读写标准鼠标和标准键盘的数据,因为它们是系统独占的(Exlusive)。 如果你是其他HID类设备,比如游戏手柄或者自定义HID设备,都可以用上面的方式来收发数据,
怎么访问我暂时也不知道,估计要用它方法,看到有些软件是用截取的手段,估计是用钩子了吧。。
最后忘记引用空间了,其实大家都知道的 using System;
using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; using System.Threading; using System.Collections; using System.IO;
还有获取报文长度的代码,如果不确定报文长度,或者为了驱动适应变化,就用一下代码来确定报文的长度
//获取设备具体信息
[DllImport(\
private unsafe static extern int HidP_GetCaps(
int pPHIDP_PREPARSED_DATA, // IN PHIDP_PREPARSED_DATA PreparsedData,
ref HIDP_CAPS myPHIDP_CAPS); // OUT PHIDP_CAPS Capabilities
[DllImport(\
private unsafe static extern int HidD_GetPreparsedData(
int hObject, // IN HANDLE HidDeviceObject,
ref int pPHIDP_PREPARSED_DATA);
// HIDP_CAPS
[StructLayout(LayoutKind.Sequential)] public unsafe struct HIDP_CAPS {
public System.UInt16 Usage; // USHORT public System.UInt16 UsagePage; // USHORT public System.UInt16 InputReportByteLength; public System.UInt16 OutputReportByteLength; public System.UInt16 FeatureReportByteLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 17)]
public System.UInt16[] Reserved; // USHORT Reserved[17]; public System.UInt16 NumberLinkCollectionNodes; public System.UInt16 NumberInputButtonCaps; public System.UInt16 NumberInputValueCaps; public System.UInt16 NumberInputDataIndices; public System.UInt16 NumberOutputButtonCaps; public System.UInt16 NumberOutputValueCaps; public System.UInt16 NumberOutputDataIndices; public System.UInt16 NumberFeatureButtonCaps; public System.UInt16 NumberFeatureValueCaps; public System.UInt16 NumberFeatureDataIndices; }
int reportLength = 8;
//获取设备发送的字节的长度(也有其他信息) int myPtrToPreparsedData = -1;
int result1 = HidD_GetPreparsedData(handle, ref myPtrToPreparsedData); HIDP_CAPS myHIDP_CAPS = new HIDP_CAPS();
int result2 = HidP_GetCaps(myPtrToPreparsedData, ref myHIDP_CAPS); reportLength = myHIDP_CAPS.InputReportByteLength;
再补充点,释放设备资源的时候需要用到
代码 //释放设备的访问
[DllImport(\)]
internal static extern int CloseHandle(int hObject); //释放设备
[DllImport(\, SetLastError = true)]
internal static extern IntPtr SetupDiDestroyDeviceInfoList(IntPtr DeviceInfoSet);
public void Dispost() {
//释放设备资源(hDevInfo是SetupDiGetClassDevs获取的) SetupDiDestroyDeviceInfoList(hDevInfo); //关闭连接(HidHandle是Create的时候获取的) CloseHandle(HidHandle); }

