// 获得GUID
[DllImport( " hid.dll " )]
public static extern void HidD_GetHidGuid( ref Guid HidGuid);
Guid guidHID = Guid.Empty;
// 过滤设备,获取需要的设备
[DllImport( " setupapi.dll " , SetLastError = true )]
public static extern IntPtr SetupDiGetClassDevs( ref Guid ClassGuid, uint Enumerator, IntPtr HwndParent, DIGCF Flags);
IntPtr hDevInfo;
// 获取设备,true获取到
[DllImport( " setupapi.dll " , CharSet = CharSet.Auto, SetLastError = true )]
public static extern Boolean SetupDiEnumDeviceInterfaces(IntPtr hDevInfo, IntPtr devInfo, ref Guid interfaceClassGuid, UInt32 memberIndex, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData);
public struct SP_DEVICE_INTERFACE_DATA
{
public int cbSize ;
public Guid interfaceClassGuid;
public int flags;
public int reserved;
}
// 获取接口的详细信息 必须调用两次 第1次返回长度 第2次获取数据
[DllImport( " setupapi.dll " , SetLastError = true , CharSet = CharSet.Auto)]
private static extern bool SetupDiGetDeviceInterfaceDetail(IntPtr deviceInfoSet, ref SP_DEVICE_INTERFACE_DATA deviceInterfaceData, IntPtr deviceInterfaceDetailData,
int deviceInterfaceDetailDataSize, ref int requiredSize, SP_DEVINFO_DATA deviceInfoData);
[StructLayout(LayoutKind.Sequential)]
public class SP_DEVINFO_DATA
{
public int cbSize = Marshal.SizeOf( typeof (SP_DEVINFO_DATA));
public Guid classGuid = Guid.Empty; // temp
public int devInst = 0 ; // dumy
public int reserved = 0 ;
}
[StructLayout(LayoutKind.Sequential, Pack = 2 )]
internal struct SP_DEVICE_INTERFACE_DETAIL_DATA
{
internal int cbSize;
internal short devicePath;
}
public enum DIGCF
{
DIGCF_DEFAULT = 0x1 ,
DIGCF_PRESENT = 0x2 ,
DIGCF_ALLCLASSES = 0x4 ,
DIGCF_PROFILE = 0x8 ,
DIGCF_DEVICEINTERFACE = 0x10
}
// 获取设备文件
[DllImport( " kernel32.dll " , SetLastError = true )]
private static extern int CreateFile(
string lpFileName, // file name
uint dwDesiredAccess, // access mode
uint dwShareMode, // share mode
uint lpSecurityAttributes, // SD
uint dwCreationDisposition, // how to create
uint dwFlagsAndAttributes, // file attributes
uint hTemplateFile // handle to template file
);
// 读取设备文件
[DllImport( " Kernel32.dll " ,SetLastError = true )]
private static extern bool ReadFile
(
IntPtr hFile,
byte [] lpBuffer,
uint nNumberOfBytesToRead,
ref uint lpNumberOfBytesRead,
IntPtr lpOverlapped
);
// 释放设备
[DllImport( " hid.dll " )]
static public extern bool HidD_FreePreparsedData( ref IntPtr PreparsedData);
// 关闭访问设备句柄,结束进程的时候把这个加上保险点
[DllImport( " kernel32.dll " )]
static public extern int CloseHandle( int hObject);
接下来是访问设备的代码
// 有些USB设备其实有很多HID设备,就是一个接口上有几个设备,这个时候需要
// 用index++来逐个循环,直到获取设备返回false后,跳出去,把获取的设备
// 路径全记录下来就好了,我这里知道具体设备号,所以没有循环,浪费我时间
// 定于句柄序号和一些参数,具体可以去网上找这些API的参数说明,后文我看能不能把资料也写上去
int HidHandle = - 1 ;
public const uint GENERIC_READ = 0x80000000 ;
public const uint GENERIC_WRITE = 0x40000000 ;
public const uint FILE_SHARE_READ = 0x00000001 ;
public const uint FILE_SHARE_WRITE = 0x00000002 ;
public const int OPEN_EXISTING = 3 ;
private void UsBMethod( int index)
{
HidD_GetHidGuid( ref guidHID);
hDevInfo = SetupDiGetClassDevs( ref guidHID, 0 , IntPtr.Zero, DIGCF.DIGCF_PRESENT | DIGCF.DIGCF_DEVICEINTERFACE);
int bufferSize = 0 ;
ArrayList HIDUSBAddress = new ArrayList();
// while (true)
// {
// 获取设备,true获取到
SP_DEVICE_INTERFACE_DATA DeviceInterfaceData = new SP_DEVICE_INTERFACE_DATA();
DeviceInterfaceData.cbSize = Marshal.SizeOf(DeviceInterfaceData);
// for (int i = 0; i < 3; i++)
// {
bool result = SetupDiEnumDeviceInterfaces(hDevInfo, IntPtr.Zero, ref guidHID, (UInt32)index, ref DeviceInterfaceData);
// }
// 第一次调用出错,但可以返回正确的Size
SP_DEVINFO_DATA strtInterfaceData = new SP_DEVINFO_DATA();
result = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, IntPtr.Zero, 0 , ref bufferSize, strtInterfaceData);
// 第二次调用传递返回值,调用即可成功
IntPtr detailDataBuffer = Marshal.AllocHGlobal(bufferSize);
SP_DEVICE_INTERFACE_DETAIL_DATA detailData = new SP_DEVICE_INTERFACE_DETAIL_DATA();
detailData.cbSize = Marshal.SizeOf( typeof (SP_DEVICE_INTERFACE_DETAIL_DATA));
Marshal.StructureToPtr(detailData, detailDataBuffer, false );
result = SetupDiGetDeviceInterfaceDetail(hDevInfo, ref DeviceInterfaceData, detailDataBuffer, bufferSize, ref bufferSize, strtInterfaceData);
if (result == false )
{
// break;
}
// 获取设备路径访
IntPtr pdevicePathName = (IntPtr)(( int )detailDataBuffer + 4 );
string devicePathName = Marshal.PtrToStringAuto(pdevicePathName);
HIDUSBAddress.Add(devicePathName);
// index++;
// break;
// }
// 连接设备文件
int aa = CT_CreateFile(devicePathName);
bool bb = USBDataRead(HidHandle);
}
// 建立和设备的连接
public unsafe int CT_CreateFile( string DeviceName)
{
HidHandle = CreateFile(
DeviceName,
GENERIC_READ, // | GENERIC_WRITE, // 读写,或者一起
FILE_SHARE_READ, // | FILE_SHARE_WRITE, // 共享读写,或者一起
0 ,
OPEN_EXISTING,
0 ,
0 );
if (HidHandle == - 1 )
{
return 0 ;
}
else
{
return 1 ;
}
}
// 根据CreateFile拿到的设备handle访问文件,并返回数据
public unsafe bool USBDataRead( int handle)
{
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;
The HID Page
For developers of USB devices in the human interface device (HID) class.
Basics
My HID FAQ.
HID webpage from the USB-IF.
Windows programming
You can use Windows' built-in HID (human interface device) drivers to communicate with devices that conform to the USB's HID class specification. There's no need for a custom driver; the device uses the drivers included in Windows. Use any programming language that supports calling API functions. The device doesn't have to have a "human interface." Any device that can function within the limits of the HID specification (control and interrupt transfers only) may be able to be designed as a HID.
Microsoft's WDK has documentation for the HID functions and an overview of how to use them. The WDK also includes the header files to use with Visual C++ programs that access HID-class devices (hidsdi.h, hidusage.h, hidpi.h).
Human Input Devices. The Windows HID API from Microsoft.
Microsoft's DirectX technology includes DirectInput, which supports communications with HID-class game controllers (in both directions, in spite of the name), without requiring custom drivers. Microsoft's DirectX Developer Center has the latest info.
Use Raw Input to read data from a specific keyboard, mouse, or game controller.
A Usenet discussion about using HIDs under Windows CE. For other posts on this topic, search the newsgroups microsoft.public.windowsce* from groups.google.com/advanced_search.
Articles
HIDs Up by Jan Axelson, Embedded Systems Programming. From Embedded Systems Programming.
Using the HID class eases the job of writing USB device drivers by Stuart Allman. From EDN.
Making USB C# friendly. Article by Ashley Deakin in VSJ.
Books
USB Complete includes three chapters on HID firmware and application programming.
Chapter 13: Human Interface Devices. From Programming the Microsoft Windows Driver Model, Second Edition by Walter Oney.
Tools
Software
HIDMaker creates device firmware and a Windows application from information you provide. Also available are the AnyHID test program and the USBWatch software-only protocol analyzer. From Trace Systems Inc.
The SimpleHIDWrite utility tests HID-class devices. The HidTest utility also tests HIDs with a variety of API calls. HidTest.zip contains the application and HidTestSource.zip contains the source files in Delphi. All from Robert Marquardt.
Robert Marquardt's HID Controller component suite for Delphi.
USB HID API Function Library. From Kadtronix.
Hardware
MouseWarrior, KeyWarrior, JoyWarrior, IO-Warrier, and IO-Warrior 24PowerVampire (for using USB as a power supply). Available as programmed chips or kits. From Code Mercenaries.
My example code
Host applications and device firmware to work with them.
Host applications
My HID applications below communicate with generic (custom) HIDs. Each supports exchanging Input, Output, and Feature reports and shows how to search for devices that use a particular interface GUID. All except the Visual Basic 6 code show how to use RegisterDeviceNotification and WM_DEVICE_CHANGE messages to detect when a device is attached or removed.
Visual Basic .NET
generic_hid_vb. Created with Visual Studio 2008 for the .NET Framework 2.0 or later. Updated 11/09/09.
Visual C# (C Sharp)
generic_hid_cs. Created with Visual Studio 2008 for the .NET Framework 2.0 or later. Updated 11/09/09.
usbhidio_V2.3.cs. My VB HIDClass application ported to C#. From Gordon Vance. (Bug report: change: if (MyEnvironment.Version >= Version98SE) to if (MyEnvironment.Version <= Version98SE).
Visual Basic 6
Visual C++ 6
Usbhidio_vc6. This project will load into and run in Visual Studio. The project requires the header files hid.lib, hid.h, and hidsdi.h from the WDK.
1. If you get this errror on attempting to compile:
DBT_DEVTYP_DEVICEINTERFACE, PDEV_BROADCAST_DEVICEINTERFACE, HDEVNOTIFY, DEVICE_NOTIFY_WINDOW_HANDLE undeclared
Set WINVER = 0x0500 or higher in stdafx.h
For more info, go to groups.google.com and search on:
"DEV_BROADCAST_DEVICEINTERFACE" "undeclared identifier"
2. HidD_GetInputReport and HidD_SetInputReport require Windows XP or later.
Generic HID device firmware
HID firmware for communicating with the Windows host code above.
Microchip PIC18F4550
generic_hid_fsusb_fw2-5.zip is is my Microchip PIC microcontroller firmware for generic HIDs. Written for the PIC 18F4550 and Microchip's C18 C compiler with Microchip's V2.5 USB Framework. See the readme file to find out how to create the project in the Framework directory structure. (The Framework includes a HID example, but my code also supports vendor-defined control transfers.) Updated 8/17/09.
Older versions
Use the newest Framework and firmware unless you have a compelling reason not to.
For the Framework V2.3. Generic_HID_c18_fsusb_fwv2-3.zip
For the Framework. V2.1. Generic_HID_C18_FSUSB
For the Framework V1.x. mchpfsusb_ghid.zipCypress Semiconductor EZ-USB FX2
fx2hid.zip runs on Cypress' FX2 EZ-USB chips at full and high speeds. It's adapted from Cypress' frameworks examples and requires the full version of the Keil C compiler.
Cypress Semiconductor Encore
Enchid.zip for Cypress Encore chips (CY637xx). Assembly code.
Cypress Semiconductor EZ-USB
fwhid.zip for Cypress EZ-USB chips. In C. More information.
Cypress Semiconductor EZ-USB Buttons and Lights
A version of John Hyde's buttons and lights code for the USBSimm module. (The module is no longer available.) My code supports interrupt Out transfers for Output reports.
Cypress Semiconductor CY63000
Usbhidio.zip (61k) contains assembly-code firmware and host software for communicating with a Cypress CY7C63000 microcontroller (obsolete). The code runs on Cypress' 3650 Developer's Kit and CY3640 Starter Kit. Cypress has discontinued the Starter Kit. The Hi-Lo EPROM programmer included in the Starter Kit was Cypress part CY3649. The host software is Visual Basic 6 code. Bug list and fixes for usbhidio.
Cypress Semiconductor CY63000 firmware plus Visual Basic code using an ActiveX Exe server
HIDDemo2.zip (70k) is an enhanced version of usbhidio. Like usbhidio that uses an ActiveX Exe server to handle reading from the device.
Other code
Code from other sources.
Device firmware for use with my .NET HID applications
These firmware examples are designed to work with my PC HID applications above.
Cypress Semiconductor 66113
Hidhub1.zip contains a version of my generic HID-class firmware for Cypress' CY7C66113 hub & peripheral chip. The firmware enumerates as a compound device made up of a 4-port hub and my usbhidio device. It runs on the 3652 development kit and will communicate with my hidvb and usbhidioc software. This code is provided by Mat Laibowitz.
Microchip PIC
Firmware for the PIC16C745/765 to enable using my HID .NET and usbhidioc software. From Microchip. For more PIC advice, see USB and PIC Microprocessors 16C745 and 18F2455 from Alan Macek.
Assembly code and C firmware for the PIC16C745 and PIC18F2455. From Bradley A. Minch at Olin College
The PICBasic Pro Basic compiler includes instructions to perform HID communications, for use with PICMicros with USB support. From microEngineering Labs Inc.
My Very First USB Peripheral. A description of a PIC16C745 HID project. From Technology Stir Fry.
More HID firmware
Atmel
Atmel's AT90USBKey demonstration board for the AT90USB AVR microcontroller has generic HID, keyboard, and mouse applications.
Automator is a HID project for the Atmel AVR-USB. Includes host code. From Objective Development Software.
Cypress Semiconductor
Example HID Firmware in C for Cypress enCoRe devices. From Stephen Santarelli.
John Hyde's USB Design By Example site has HID examples in Visual Basic and Visual C++. I have a version of the buttons and lights firmware that supports interrupt Out transfers.
The MO1002 USB to UART is a HID device that translates between asynchronous serial data and USB using Windows' HID drivers. Includes schematics, firmware, and a Visual C++ application. The chip used is Cypress' CY7C63001. From Moto Development Group.
Microchip
Microchip's USB Framework firmware includes HID examples..
FMSUSB is a RC(PPM) to FMS (Flying Model Simulator) USB interface. Uses a PIC16C745. From Walter Zanette.
A firmware-only HID (no hardware device controller) using a Microchip 16F84A to control a parallel LCD module (HD44780 compatible) via USB. (Spanish)
RcJoystick NG is an interface between a USB port and the buddy box connector on many RC Transmitters. From Alessio e Andrea.
ST-Ericsson (formerly NXP Semiconductors/Philips)
Interfacing a Game Boy Advance to a PC using a PIC16F877 and PDIUSBD12. From Rob Meerman.
Host code
HID USB Driver / Library. A C# DLL. From Florian Leitner.
USB Hid Device Library for .NET. From Mike O'Brien.
HID component for C# .NET. A project from the Avans Hogeschool in The Netherlands.
Controlling the Logitech iFeel Mouse. Experiments with force feedback. Daniel C. Moore