using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace WindowsApplication1 { class Class1 { [DllImport("kernel32.dll")] private static extern IntPtr CreateFile( String lpFileName, UInt32 dwDesiredAccess, UInt32 dwShareMode, IntPtr lpSecurityAttributes, UInt32 dwCreationDisposition, UInt32 dwFlagsAndAttributes, IntPtr hTemplateFile ); [DllImport("Kernel32.dll")] private static extern bool ReadFile( IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, ref uint lpNumberOfBytesRead, IntPtr lpOverlapped ); [DllImport("Kernel32.dll")] private static extern bool WriteFile( IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, ref uint lpNumberOfBytesWritten, IntPtr lpOverlapped ); [DllImport("kernel32.dll")] private static extern bool CloseHandle( IntPtr hObject ); //-------------------------------------------------------------------------------- IntPtr hFile; private const UInt32 GENERIC_READ = 0x80000000; private const UInt32 GENERIC_WRITE = 0x40000000; private const UInt32 OPEN_EXISTING = 3; private const Int32 INVALID_HANDLE_VALUE = -1; private const int USB_WRITENUM = 8; private const int USB_READNUM = 8; private byte[] m_rd_data = new byte[USB_READNUM]; public byte[] rd_data { get { return m_rd_data; } set { m_rd_data = value; } } private byte[] m_wr_data = new byte[USB_WRITENUM]; public byte[] wr_data { get { return m_wr_data; } set { m_wr_data = value; } } public bool OnInitUSB() { hFile = IntPtr.Zero; string deviceName = string.Empty; deviceName = "在这里写上你的设备的地址"; hFile = CreateFile( deviceName, GENERIC_READ | GENERIC_WRITE, 0, IntPtr.Zero, OPEN_EXISTING, 0, IntPtr.Zero ); return hFile.ToInt32() == INVALID_HANDLE_VALUE ? false : true; } public bool USBDataRead() { uint read = 0; return ReadFile(hFile, m_rd_data, (uint)USB_READNUM, ref read, IntPtr.Zero); } public bool USBDataWrite() { uint written = 0; return WriteFile(hFile, m_wr_data, (uint)USB_WRITENUM, ref written, IntPtr.Zero); } public void CloseConnection() { if (hFile.ToInt32() != INVALID_HANDLE_VALUE) { CloseHandle(hFile); hFile = IntPtr.Zero; } } } }
C#与USB设备通信 kernel32.dll
猜你喜欢
转载自blog.csdn.net/qq61394323/article/details/54089880
今日推荐
周排行