[StructLayout(LayoutKind.Sequential,Pack=4)] public struct OVERLAPPED { public IntPtr Internal; public IntPtr InternalHigh; public UInt32 Offset; public UInt32 OffsetHigh; public IntPtr hEvent; } [DllImport("kernel32.dll", SetLastError = true , CallingConvention = CallingConvention.Winapi)] private static extern UInt32 WriteFile(IntPtr hFile, byte[] lpBuffer , UInt32 nNumberOfBytesToWrite , ref UInt32 lpNumberOfBytesWritten , ref OVERLAPPED lpOverlapped); protected System.IO.Ports.SerialPort m_sp = new System.IO.Ports.SerialPort(); protected OVERLAPPED m_ov; static IntPtr GetCommHandle(System.IO.Ports.SerialPort sp) {//獲得串口控制代碼,供 Win32 API 使用 IntPtr hComm = IntPtr.Zero; if (sp != null) { object stream = typeof(System.IO.Ports.SerialPort).GetField("internalSerialStream", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(sp); var handle = (Microsoft.Win32.SafeHandles.SafeFileHandle)stream.GetType().GetField("_handle", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance).GetValue(stream); hComm = handle.DangerousGetHandle(); } return hComm; } |