新手跪求怎么用C#做USB通讯!!
我要做一个充值机的充值程序,可以读卡充值,充值机不是用串口而是用的USB,我要怎么样才能把命令帧通过USB发送给卡机,然后在接收卡机回传的数据呢。
[解决办法]
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 deviceInterfaceDetailD ata, 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();