public static extern unsafe bool DeviceIoControl( SafeObjectHandle hDevice, uint dwIoControlCode, IntPtr inBuffer, int nInBufferSize, IntPtr outBuffer, int nOutBufferSize, out int pBytesReturned, OVERLAPPED* lpOverlapped);
internal Win32Ovrlap(IntPtr handle, IntPtr evHandle) { this.handle = handle; // Create, init overlap. this.ol = new OVERLAPPED(); this.ol.offset = 0; this.ol.offsetHigh = 0; this.ol.hEvent = evHandle; // Create memory pointer & copy to unmanaged memory. if(evHandle != IntPtr.Zero) { this.memPtr = Marshal.AllocHGlobal(Marshal.SizeOf(this.ol)); Marshal.StructureToPtr(this.ol, this.memPtr, false); } return; }
public static extern bool WaitCommEvent( IntPtr hFile, // handle to comm device out int lpEvtMask, // event type ref OVERLAPPED lpOverlapped // overlapped structure );
static public extern int GetOverlappedResult(SafeFileHandle hFile, ref OVERLAPPED lpOverlapped, ref int lpNumberOfBytesTransferred, int bWait);//type changed by Onur for 64-bit compatability
static public extern int ReadFile(int hFile, ref byte lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
public static extern bool ReadFile(int hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, ref uint lpNumberofBytesRead, ref OVERLAPPED lpOverlapped);
public static extern Boolean ReadFile(IntPtr hFile, Byte[] lpBuffer, UInt32 nNumberOfBytesToRead, out UInt32 nNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
public static extern Int32 ReadFile(SafeFileHandle hFile, ref Byte lpBuffer, Int32 nNumberOfBytesToRead, ref Int32 lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
public static extern bool UnlockFileEx( SafeFileHandle hFile, uint dwReserved, uint nNumberOfBytesToUnlockLow, uint nNumberOfBytesToUnlockHigh, ref OVERLAPPED lpOverlapped);
// 시리얼 포트의 Overlapped 작업의 결과에 대해 반환 // lpOverlapped->hEvent : 전송이 완료된 후 시그널될 이벤트 핸들. AxsPortWriteFile, AxsPortReadFile 함수를 사용하기전에 이 값을 설정함. // lpNumberOfBytesTransferred: 실제 전송이 완료된 바이트 크기를 얻기 위한 변수포인트 // bWait: I/O 연산이 끝나지않은 상황에서의 처리를 결정 // [0]: I/O연산이 끝날때까지 기다림 // [1]: I/O연산이 끝나지 않아도 반환함 [DllImport("AXL.dll")] public static extern uint AxsPortGetOverlappedResult(int nPortNo, ref OVERLAPPED lpOverlapped, out uint lpNumberOfBytesTransferred, bool bWait);
public static extern bool UnlockFileEx(SafeFileHandle handle, uint reserved, uint countLow, uint countHigh, ref OVERLAPPED overlapped);
[DllImport("kernel32.dll")] private static extern int WriteFile( int hFile, byte[] Buffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
// 시리얼 포트의 데이타를 읽음 // lpBuffer : 장치에 쓸 데이터를 담는 버퍼의 포인트값 // nNumberOfBytesToRead : lpBuffer가 가리키는 버퍼의 크기를 바이트로 지정 // lpNumberOfBytesRead : 실제로 읽혀진 바이트 수를 반환(None Overrapped 일경우) // lpOverlapped : 비동기를 위한 OVERLAPPED 구조체의 포인트 값 [DllImport("kernel32.dll")] public static extern uint AxsPortReadFile(int nPortNo, IntPtr lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
[DllImport("kernel32.dll")] private static extern int WaitCommEvent(int hFile, ref EventMasks Mask, ref OVERLAPPED lpOverlap);
[DllImport("kernel32.dll")] private static extern int ReadFile(int hFile, byte[] Buffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
[DllImport("kernel32.dll")] private static extern int GetOverlappedResult(int hFile, ref OVERLAPPED lpOverlapped, ref int lpNumberOfBytesTransferred, int bWait);
public static extern int WSASend([In] IntPtr s, [In] WSABUF[] lpBuffers, int dwBufferCount, [Out] out int lpNumberOfBytesSent, int dwFlags, [In] ref OVERLAPPED lpOverlapped, [In] TOAPI.Kernel32.Kernel32.FileIOCompletionRoutine lpCompletionRoutine);
public static extern bool ReadFile(IntPtr hFile, [MarshalAs(UnmanagedType.LPArray)] byte[] aSegementArray, int nNumberOfBytesToRead, ref int lpReserved, [In] ref OVERLAPPED lpOverlapped); // System.Threading.NativeOverlapped
public static extern bool UnlockFileEx(SafeFileHandle hFile, uint dwReserved, uint nNumberOfBytesToUnlockLow, uint nNumberOfBytesToUnlockHigh, ref OVERLAPPED lpOverlapped);
private static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, out int lpNumberOfBytesWritten, out OVERLAPPED lpOverlapped);
public static extern int WriteFileGather(SafeFileHandle hFile, [In] ref FILE_SEGMENT_ELEMENT[] aSegmentArray, uint nNumberOfBytesToWrite, IntPtr lpReserved, ref OVERLAPPED lpOverlapped);
public static extern bool GetOverlappedResultEx( SafeFileHandle hFile, ref OVERLAPPED lpOverlapped, out uint lpNumberOfBytesTransferred, uint dwMilliseconds, bool bAlertable);
/// <summary> /// 写入数据 /// </summary> /// <param name="date">数据</param> public int Send(int commHandle,byte[] date) { if (commHandle != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesWritten = 0; WriteFile(commHandle, date, date.Length, ref BytesWritten, ref ovlCommPort); Console.WriteLine("SerialsBSTLib发送:" + BitConverter.ToString(date)); return BytesWritten; } else { throw (new ApplicationException("无法打开串口,可能该串口不存在或者已被其他应用程序使用!")); } }
protected static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
public static extern unsafe bool GetOverlappedResult( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped, out int lpNumberOfBytesTransferred, bool bWait);
private void ReceiveSendThreadSerial() { var buffer = new byte[64]; var restart = false; var sendMessageBytes = new byte[0]; int sentBytes = 0; var sendTimeout = new Stopwatch(); var portHandle = IntPtr.Zero; Thread.Sleep(1000); _receivedBytes.Clear(); var resetEvent = new AutoResetEvent(false); var overlapped = new OVERLAPPED(); var ptrOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(overlapped)); overlapped.Offset = 0; overlapped.OffsetHigh = 0; overlapped.hEvent = resetEvent.SafeWaitHandle.DangerousGetHandle(); Marshal.StructureToPtr(overlapped, ptrOverlapped, true); bool waitingRead = false; var writeResetEvent = new AutoResetEvent(false); var writeOverlapped = new OVERLAPPED(); var ptrWriteOverlapped = Marshal.AllocHGlobal(Marshal.SizeOf(writeOverlapped)); writeOverlapped.Offset = 0; writeOverlapped.OffsetHigh = 0; writeOverlapped.hEvent = writeResetEvent.SafeWaitHandle.DangerousGetHandle();; Marshal.StructureToPtr(writeOverlapped, ptrWriteOverlapped, true); bool waitingWrite = false; while (!_receiveSendThreadStopped) { try { if (portHandle == IntPtr.Zero) { int portnumber = Int32.Parse(_comPort.Replace("COM", String.Empty)); string comPort = _comPort; if (portnumber > 9) { comPort = String.Format("\\\\.\\{0}", _comPort); } portHandle = Win32Com.CreateFile(comPort, Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero, Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (portHandle == (IntPtr)Win32Com.INVALID_HANDLE_VALUE) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) { throw new Exception(String.Format("Access denied for port {0}", _comPort)); } else { throw new Exception(String.Format("Failed to open port {0}", _comPort)); } } COMMTIMEOUTS commTimeouts = new COMMTIMEOUTS { ReadIntervalTimeout = 5, ReadTotalTimeoutConstant = 0, ReadTotalTimeoutMultiplier = 0, WriteTotalTimeoutConstant = 0, WriteTotalTimeoutMultiplier = 0 }; DCB dcb = new DCB(); dcb.Init(false, false, false, 0, false, false, false, false, 0); dcb.BaudRate = _baudRate; dcb.ByteSize = 8; dcb.Parity = 0; dcb.StopBits = 0; if (!Win32Com.SetupComm(portHandle, 8192, 4096)) { throw new Exception(String.Format("Failed to set queue settings for port {0}", _comPort)); } if (!Win32Com.SetCommState(portHandle, ref dcb)) { throw new Exception(String.Format("Failed to set comm settings for port {0}", _comPort)); } if (!Win32Com.SetCommTimeouts(portHandle, ref commTimeouts)) { throw new Exception(String.Format("Failed to set comm timeouts for port {0}", _comPort)); } if (_rtsCts) { if (!Win32Com.EscapeCommFunction(portHandle, Win32Com.CLRRTS)) { throw new Exception(String.Format("Failed to reset RTS pin{0}", _comPort)); } } Thread.Sleep(1000); } if (!Win32Com.GetHandleInformation(portHandle, out uint lpdwFlags)) { throw new Exception(String.Format("Port {0} went offline", _comPort)); } if (!waitingRead) { waitingRead = true; if (!Win32Com.ReadFile(portHandle, buffer, (uint)buffer.Length, out uint readBytes, ptrOverlapped)) { if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) { throw new Exception(String.Format("Failed to read port {0}", _comPort)); } } } else { if (resetEvent.WaitOne(10)) { waitingRead = false; if (!Win32Com.GetOverlappedResult(portHandle, ptrOverlapped, out uint readBytes, false)) { throw new Exception(String.Format("Failed to read port {0}", _comPort)); } for (int i = 0; i < readBytes; i++) { _receivedBytes.Add(buffer[i]); } } } if (_sendMessageQueue.Count > 0 && sendMessageBytes.Length == 0) { lock (_syncobject) sendMessageBytes = _sendMessageQueue.Dequeue(); sentBytes = 0; } if (sendMessageBytes.Length > 0) { if (_rtsCts) { if (!Win32Com.EscapeCommFunction(portHandle, Win32Com.SETRTS)) { lock (_syncobject) _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to set RTS pin{0}", _comPort)))); } } uint lpmodemstat = 0; if (_rtsCts) { if (!Win32Com.GetCommModemStatus(portHandle, out lpmodemstat)) { _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to get RTS pin{0}", _comPort)))); } } if ((lpmodemstat & Win32Com.MS_CTS_ON) > 0 || !_rtsCts) { if (!waitingWrite) { waitingWrite = true; sendTimeout.Restart(); if (!Win32Com.WriteFile(portHandle, sendMessageBytes, (uint)sendMessageBytes.Length, out uint sent, ptrWriteOverlapped)) { if (Marshal.GetLastWin32Error() != Win32Com.ERROR_IO_PENDING) { _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to write to port {0}", _comPort)))); } } } else { if (writeResetEvent.WaitOne(0)) { if (!Win32Com.GetOverlappedResult(portHandle, ptrWriteOverlapped, out uint sent, false)) { _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to write to port {0}", _comPort)))); } sentBytes += (int)sent; } } if (sentBytes == sendMessageBytes.Length || sendTimeout.ElapsedMilliseconds > 200) { if (sendTimeout.ElapsedMilliseconds > 100) { lock (_syncobject) _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to write all bytes to port {0}", _comPort)))); } if (_rtsCts) { if (!Win32Com.EscapeCommFunction(portHandle, Win32Com.CLRRTS)) { lock (_syncobject) _sendExceptionQueue.Enqueue(new SBPSendExceptionEventArgs(new Exception(String.Format("Failed to reset RTS pin{0}", _comPort)))); } } sendMessageBytes = new byte[0]; waitingWrite = false; } } } ProcessReading(restart); restart = false; } catch (Exception e) { _receivedBytes.Clear(); Win32Com.CancelIo(portHandle); Win32Com.CloseHandle(portHandle); portHandle = IntPtr.Zero; restart = true; lock (_syncobject) _readExceptionQueue.Enqueue(new SBPReadExceptionEventArgs(e)); Thread.Sleep(5000); } } Win32Com.CancelIo(portHandle); Win32Com.CloseHandle(portHandle); Marshal.FreeHGlobal(ptrOverlapped); Marshal.FreeHGlobal(ptrWriteOverlapped); }
///<summary> ///读取串口返回的数据 ///</summary> ///<param name="NumBytes">数据长度</param> public int Read(ref byte[] bytData, int NumBytes) { if (hComm != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesRead = 0; ReadFile(hComm, bytData, NumBytes, ref BytesRead, ref ovlCommPort); return BytesRead; } else { return -1; } }
public static extern Boolean WriteFile(IntPtr fFile, Byte[] lpBuffer, UInt32 nNumberOfBytesToWrite, out UInt32 lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
public byte[] Readport(int NumBytes) { byte[] BufBytes; byte[] OutBytes; BufBytes = new byte[NumBytes]; if (hComm != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesRead = 0; ReadFile(hComm, BufBytes, NumBytes, ref BytesRead, ref ovlCommPort); OutBytes = new byte[BytesRead]; Array.Copy(BufBytes, OutBytes, BytesRead); } else { throw (new ApplicationException("串口未打开!")); } return OutBytes; }
///<summary> ///向串口写数据 ///</summary> ///<param name="WriteBytes">数据数组</param> public int Write(byte[] WriteBytes, int intSize) { if (hComm != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesWritten = 0; WriteFile(hComm, WriteBytes, intSize, ref BytesWritten, ref ovlCommPort); return BytesWritten; } else { return -1; } }
public static extern bool LockFileEx([In] IntPtr hFile, uint dwFlags, uint dwReserved, uint nNumberOfBytesToLockLow, uint nNumberOfBytesToLockHigh, ref OVERLAPPED lpOverlapped);
public static unsafe extern bool ReadFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToRead, NullableUInt32 lpNumberOfBytesRead, OVERLAPPED* lpOverlapped);
public static extern bool GetOverlappedResult( IntPtr hFile, // handle to file, pipe, or device ref OVERLAPPED lpOverlapped, // overlapped structure ref int lpNumberOfBytesTransferred, // bytes transferred bool bWait // wait option );
public static unsafe extern bool WriteFile( SafeObjectHandle hFile, void* lpBuffer, uint nNumberOfBytesToWrite, NullableUInt32 lpNumberOfBytesWritten, OVERLAPPED* lpOverlapped);
private static extern bool ReadFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
public static unsafe extern bool CancelIoEx( SafeObjectHandle hFile, OVERLAPPED* lpOverlapped);
public static extern bool ReadFile(SafeFileHandle hFile, IntPtr lpBuffer, uint nNumberOfBytesToRead, IntPtr lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
static internal extern bool ReadFile(IntPtr hFile, ref byte lpBuffer, Int32 nNumberOfBytesToRead, ref Int32 lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
public static extern int WriteFileEx(SafeFileHandle hFile, IntPtr lpBuffer, uint nNumberOfBytesToWrite, ref OVERLAPPED lpOverlapped, FileIOCompletionRoutine lpCompletionRoutine);
static internal extern bool WriteFile(IntPtr hFile, byte[] lpBuffer, Int32 nNumberOfBytesToWrite, ref Int32 lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
public unsafe static extern bool ReadDirectoryChangesW(IntPtr hDirectory, byte *lpBuffer, int nBufferLength, bool bWatchSubtree, int dwNotifyFilter, int * lpBytesReturned, ref OVERLAPPED lpOverlapped, LpoverlappedCompletionRoutine lpCompletionRoutine);
/// <summary> /// Opens the com port and configures it with the required settings /// </summary> /// <returns>false if the port could not be opened</returns> public bool Open() { var portDcb = new DCB(); var commTimeouts = new COMMTIMEOUTS(); var wo = new OVERLAPPED(); if (_online) { Console.WriteLine("COM port already open, bailing out of ComPort.Open"); return(false); } _hPort = Win32Com.CreateFile(PortName, Win32Com.GENERIC_READ | Win32Com.GENERIC_WRITE, 0, IntPtr.Zero, Win32Com.OPEN_EXISTING, Win32Com.FILE_FLAG_OVERLAPPED, IntPtr.Zero); if (_hPort == (IntPtr)Win32Com.INVALID_HANDLE_VALUE) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_ACCESS_DENIED) { return(false); } throw new CommPortException("Port Open Failure"); } _online = true; commTimeouts.ReadIntervalTimeout = 0; commTimeouts.ReadTotalTimeoutConstant = 0; commTimeouts.ReadTotalTimeoutMultiplier = 0; commTimeouts.WriteTotalTimeoutConstant = SendTimeoutConstant; commTimeouts.WriteTotalTimeoutMultiplier = SendTimeoutMultiplier; portDcb.Init(((Parity == Parity.Odd) || (Parity == Parity.Even)), TxFlowCts, TxFlowDsr, (int)UseDtr, RxGateDsr, !TxWhenRxXoff, TxFlowX, RxFlowX, (int)UseRts); portDcb.BaudRate = BaudRate; portDcb.ByteSize = (byte)DataBits; portDcb.Parity = (byte)Parity; portDcb.StopBits = (byte)StopBits; portDcb.XoffChar = (byte)XoffChar; portDcb.XonChar = (byte)XonChar; portDcb.XoffLim = (short)RxHighWater; portDcb.XonLim = (short)RxLowWater; if ((RxQueue != 0) || (TxQueue != 0)) { if (!Win32Com.SetupComm(_hPort, (uint)RxQueue, (uint)TxQueue)) { ThrowException("Bad queue settings"); } } if (!Win32Com.SetCommState(_hPort, ref portDcb)) { ThrowException("Bad com settings"); } if (!Win32Com.SetCommTimeouts(_hPort, ref commTimeouts)) { ThrowException("Bad timeout settings"); } _stateBrk = 0; if (UseDtr == HsOutput.None) { _stateDtr = 0; } if (UseDtr == HsOutput.Online) { _stateDtr = 1; } if (UseRts == HsOutput.None) { _stateRts = 0; } if (UseRts == HsOutput.Online) { _stateRts = 1; } _checkSends = CheckAllSends; wo.Offset = 0; wo.OffsetHigh = 0; wo.hEvent = _checkSends ? _writeEvent.Handle : IntPtr.Zero; _ptrUwo = Marshal.AllocHGlobal(Marshal.SizeOf(wo)); Marshal.StructureToPtr(wo, _ptrUwo, true); _writeCount = 0; _rxException = null; _rxExceptionReported = false; _rxThread = new Thread(ReceiveThread) { Name = "CommBaseRx", Priority = ThreadPriority.AboveNormal }; //If not set to true, my application process will not exit completely after UI closed _rxThread.IsBackground = true; _rxThread.Start(); Thread.Sleep(1); //Give rx thread time to start. By documentation, 0 should work, but it does not! _auto = false; if (AfterOpen()) { _auto = AutoReopen; return(true); } Close(); return(false); }
/// <summary> /// 读取数据 /// </summary> /// <param name="numBytes">要读取的字节数</param> /// <returns>字节数组</returns> public byte[] Read(int commHandle,int numBytes) { // 创建中间变量存储数据 byte[] BufBytes; byte[] OutBytes = null; BufBytes = new byte[numBytes]; // 读取数据并返回 if (commHandle != INVALID_HANDLE_VALUE) { OVERLAPPED ovlCommPort = new OVERLAPPED(); int BytesRead = 0; ReadFile(commHandle, BufBytes, numBytes, ref BytesRead, ref ovlCommPort); OutBytes = new byte[BytesRead]; Array.Copy(BufBytes, OutBytes, BytesRead); } else { throw (new ApplicationException("串口未打开!")); } return OutBytes; }
private void ReceiveThread() { var buf = new Byte[1]; var sg = new AutoResetEvent(false); var ov = new OVERLAPPED(); var unmanagedOv = Marshal.AllocHGlobal(Marshal.SizeOf(ov)); ov.Offset = 0; ov.OffsetHigh = 0; ov.hEvent = sg.Handle; Marshal.StructureToPtr(ov, unmanagedOv, true); uint eventMask = 0; var uMask = Marshal.AllocHGlobal(Marshal.SizeOf(eventMask)); try { while (true) { if (!Win32Com.SetCommMask(_hPort, Win32Com.EV_RXCHAR | Win32Com.EV_TXEMPTY | Win32Com.EV_CTS | Win32Com.EV_DSR | Win32Com.EV_BREAK | Win32Com.EV_RLSD | Win32Com.EV_RING | Win32Com.EV_ERR)) { throw new CommPortException("IO Error [001]"); } Marshal.WriteInt32(uMask, 0); if (!Win32Com.WaitCommEvent(_hPort, uMask, unmanagedOv)) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) { sg.WaitOne(); } else { throw new CommPortException("IO Error [002]"); } } eventMask = (uint)Marshal.ReadInt32(uMask); if ((eventMask & Win32Com.EV_ERR) != 0) { UInt32 errs; if (Win32Com.ClearCommError(_hPort, out errs, IntPtr.Zero)) { var s = new StringBuilder("UART Error: ", 40); if ((errs & Win32Com.CE_FRAME) != 0) { s = s.Append("Framing,"); } if ((errs & Win32Com.CE_IOE) != 0) { s = s.Append("IO,"); } if ((errs & Win32Com.CE_OVERRUN) != 0) { s = s.Append("Overrun,"); } if ((errs & Win32Com.CE_RXOVER) != 0) { s = s.Append("Receive Cverflow,"); } if ((errs & Win32Com.CE_RXPARITY) != 0) { s = s.Append("Parity,"); } if ((errs & Win32Com.CE_TXFULL) != 0) { s = s.Append("Transmit Overflow,"); } s.Length = s.Length - 1; throw new CommPortException(s.ToString()); } throw new CommPortException("IO Error [003]"); } if ((eventMask & Win32Com.EV_RXCHAR) != 0) { uint gotbytes; do { if (!Win32Com.ReadFile(_hPort, buf, 1, out gotbytes, unmanagedOv)) { if (Marshal.GetLastWin32Error() == Win32Com.ERROR_IO_PENDING) { Win32Com.CancelIo(_hPort); gotbytes = 0; } else { throw new CommPortException("IO Error [004]"); } } if (gotbytes == 1) { OnRxChar(buf[0]); } } while (gotbytes > 0); } if ((eventMask & Win32Com.EV_TXEMPTY) != 0) { OnTxDone(); } if ((eventMask & Win32Com.EV_BREAK) != 0) { OnBreak(); } uint i = 0; if ((eventMask & Win32Com.EV_CTS) != 0) { i |= Win32Com.MS_CTS_ON; } if ((eventMask & Win32Com.EV_DSR) != 0) { i |= Win32Com.MS_DSR_ON; } if ((eventMask & Win32Com.EV_RLSD) != 0) { i |= Win32Com.MS_RLSD_ON; } if ((eventMask & Win32Com.EV_RING) != 0) { i |= Win32Com.MS_RING_ON; } if (i != 0) { uint f; if (!Win32Com.GetCommModemStatus(_hPort, out f)) { throw new CommPortException("IO Error [005]"); } OnStatusChange(new ModemStatus(i), new ModemStatus(f)); } } } catch (Exception e) { if (uMask != IntPtr.Zero) { Marshal.FreeHGlobal(uMask); } if (unmanagedOv != IntPtr.Zero) { Marshal.FreeHGlobal(unmanagedOv); } if (!(e is ThreadAbortException)) { _rxException = e; OnRxException(e); } } }
internal static extern bool GetOverlappedResult( IntPtr hFile, ref OVERLAPPED lpOverlapped, out int lpNumberOfBytesTransferred, bool bWait );
internal static extern bool ReadFileOverlapped(IntPtr hFile, ref byte lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, ref OVERLAPPED lpOverlapped);
public static extern unsafe bool TransactNamedPipe( SafeObjectHandle hNamedPipe, void* lpInBuffer, int nInBufferSize, void* lpOutBuffer, int nOutBufferSize, out int lpBytesRead, OVERLAPPED* lpOverlapped);
internal static extern bool WriteFileOverlapped(IntPtr hFile, ref byte lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
public static extern unsafe bool ConnectNamedPipe( SafeObjectHandle hNamedPipe, OVERLAPPED* lpOverlapped);
internal static extern bool ReadFile( SafeFileHandle hFile, Byte[] aBuffer, UInt32 cbToRead, IntPtr cbThatWereRead, ref OVERLAPPED pOverlapped);
public static extern bool WriteFile(int hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, ref uint lpNumberOfBytesWritten, ref OVERLAPPED lpOverlapped);
internal static extern bool WriteFile( SafeFileHandle hFile, Byte[] aBuffer, UInt32 cbToWrite, IntPtr cbThatWereWritten, ref OVERLAPPED pOverlapped);
private static extern bool WriteFile(int hFile, byte[] lpBuffer, int nNumberOfBytesToWriter, out int lpNumberOfBytesWriten, out OVERLAPPED lpOverLapped);
static extern bool GetOverlappedResult(SafeFileHandle hFile, [In] ref OVERLAPPED lpOverlapped, out uint lpNumberOfBytesTransferred, bool bWait);
public static extern Boolean WaitCommEvent(IntPtr hFile, ref Int32 lpEvtMask, ref OVERLAPPED lpOverlapped);
private static extern bool WaitCommEvent( int hFile, int dwEvtMask, ref OVERLAPPED lpOverlapped );
public static extern Boolean GetOverlappedResult(IntPtr hFile, ref OVERLAPPED lpOverlapped, ref UInt32 nNumberOfBytesTransferred, Boolean bWait);
public static extern bool WaitCommEvent(IntPtr hFile, ref int lpEvtMask, ref OVERLAPPED lpOverlapped);