p; dcbCommPort.flags = dcbCommPort.flags Or (1) If Parity > 0 Then ''''//dcb.fParity=1 dcbCommPort.flags = dcbCommPort.flags Or (2) End If dcbCommPort.Parity = Parity dcbCommPort.ByteSize = ByteSize dcbCommPort.StopBits = StopBits If SetCommState(hComm, dcbCommPort) = False Then ''''//uint ErrorNum=GetLastError(); Throw (New ApplicationException("非法操作,不能打开串口!")) End If ''''//unremark to see if setting took correctly ''''//DCB dcbCommPort2 = new DCB(); ''''//GetCommState(hComm, ref dcbCommPort2); Opened = True End Sub Public Sub Close() If hComm <> INVALID_HANDLE_VALUE Then CloseHandle(hComm) End If End Sub Public Function Read(ByVal NumBytes As Integer) As Byte() Dim BufBytes(NumBytes) As Byte Dim OutBytes(0) As Byte If (hComm <> INVALID_HANDLE_VALUE) Then Dim ovlCommPort As New OVERLAPPED Dim BytesRead As Integer = 0 ReadFile(hComm, BufBytes, NumBytes, BytesRead, ovlCommPort) Array.Copy(BufBytes, OutBytes, BytesRead) Else Throw (New ApplicationException("串口未打开!")) End If Return OutBytes End Function
Public Sub Write(ByVal WriteBytes As Byte()) If (hComm <> INVALID_HANDLE_VALUE) Then Dim ovlCommPort As New OVERLAPPED Dim BytesWritten As Integer WriteFile(hComm, WriteBytes, WriteBytes.Length, BytesWritten, ovlCommPort) Else Throw (New ApplicationException("串口未打开!")) End If End Sub End Class End Namespace