• 全部
  • VBS
  • .NET技术
  • VBA
  • VB网络编程
  • VB多媒体
  • VB数据库
  • VB控件
  • VB COM/DCOM
  • VB基础类
  • VB API
  • 问答

SerialPort接收问题

zuiya1978 2008-12-26 07:59:32
SerialPort接收问题!
在vb.net中SerialPort接收问题,不能接收汉字,接收不完全!有乱码!请专家给出一个简单的接收数据的例子
谢谢!!!
...全文
1545 点赞 收藏 17
写回复
17 条回复
切换为时间正序
当前发帖距今超过3年,不再开放新的回复
发表回复
an_ba 2012-02-22
..123456
回复
az10000nq 2011-09-20
好长 值得一看 但是我是新手u……
回复
这个我得打个记号,改天认真看看
回复
yan_terry 2010-07-30
mark
回复
Missa 2009-09-27
只能说 5楼的兄弟很强悍
回复
yifan__ 2009-09-24
收藏~~
回复
泉畔人家 2009-07-15
mark
回复
ineedchrist 2009-07-14

#Region "Protected Routines"
Protected Sub OnCommEventReceived(ByVal source As CommPort, ByVal mask As EventMasks)

Dim del As CommEventHandler = Me.CommEventEvent
If (Not del Is Nothing) Then
Dim SafeInvoker As ISynchronizeInvoke
Try
SafeInvoker = DirectCast(del.Target, ISynchronizeInvoke)
Catch
End Try
If (Not SafeInvoker Is Nothing) Then
SafeInvoker.Invoke(del, New Object() {source, mask})
Else
del.Invoke(source, mask)
End If
End If
End Sub
#End Region
'记日志
Public Sub SysLog(ByVal strMsg As String)
Dim strFile As String
strFile = Now.Year.ToString + Now.Month.ToString + Now.Day.ToString + "client.log"
Dim objW As New IO.StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
objW.Close()
Dim objWriter As New IO.StreamWriter(File.Open(strFile, FileMode.Append))
objWriter.WriteLine(strMsg)
objWriter.Close()
End Sub
End Class

#End Region

#Region "Exceptions"
Public Class CIOChannelException : Inherits ApplicationException

Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
Sub New(ByVal Message As String, ByVal InnerException As Exception)
MyBase.New(Message, InnerException)
End Sub
End Class
Public Class IOTimeoutException : Inherits CIOChannelException

Sub New(ByVal Message As String)
MyBase.New(Message)
End Sub
Sub New(ByVal Message As String, ByVal InnerException As Exception)
MyBase.New(Message, InnerException)
End Sub
End Class

#End Region
End Namespace
回复
ineedchrist 2009-07-14
 '得到反回的数据(16进制)
Overridable ReadOnly Property InputStream() As Byte()
Get
Return mabtRxBuf
End Get
End Property
'得到返回的数据(文本)
Overridable ReadOnly Property InputStreamString() As String
Get
Dim oEncoder As New System.Text.ASCIIEncoding
Dim oEnc As Encoding = Encoding.GetEncoding(1252)
'-------------------------------------------------------------
If Not Me.InputStream Is Nothing Then
Return oEnc.GetString(Me.InputStream)
Else
Return Nothing
End If

End Get
End Property

Public Property UseXonXoff() As Boolean
Get
Return mbUseXonXoff
End Get
Set(ByVal Value As Boolean)
mbUseXonXoff = Value
End Set
End Property
Public Sub EnableEvents()
Try
If mhRS.ToInt32 <= 0 Then
Throw New ApplicationException("使用该方法前需要初始化并打开串口")
Else
If moEvents Is Nothing Then
mbEnableEvents = True
moEvents = New Thread(AddressOf pEventsWatcher)
moEvents.IsBackground = True
moEvents.Start()
End If
End If
Catch ex As Exception
SysLog("CommPort-EnableEvents出现异常:" + ex.Message)
End Try

End Sub
Public Sub DisableEvents()
Try
If mbEnableEvents = True Then
SyncLock Me
mbEnableEvents = False
End SyncLock
If muOvlE.hEvent.ToInt32 <> 0 Then SetEvent(muOvlE.hEvent)
moEvents = Nothing
End If
Catch ex As Exception
SysLog("CommPort-DisableEvents出现异常:" + ex.Message)
End Try

End Sub


Public Sub SetBreak()
Try
If mhRS.ToInt32 > 0 Then
If SetCommBreak(mhRS) = False Then Throw New Win32Exception
End If
Catch ex As Exception
SysLog("CommPort-SetBreak出现异常:" + ex.Message)
End Try

End Sub

Public Sub ClearBreak()
Try
If mhRS.ToInt32 > 0 Then
If ClearCommBreak(mhRS) = False Then Throw New Win32Exception
End If
Catch ex As Exception
SysLog("CommPort-ClearBreak出现异常:" + ex.Message)
End Try
End Sub


#Region "Finalize"
Protected Overrides Sub Finalize()
Try
If Not mbDisposed Then
If mbEnableEvents Then Me.DisableEvents()
Close()
End If
Finally
MyBase.Finalize()
End Try
End Sub
#End Region

#Region "Private Routines"
Private Sub pSetTimeout()

Dim uCtm As COMMTIMEOUTS
If mhRS.ToInt32 <= 0 Then
Exit Sub
Else
With uCtm
.ReadIntervalTimeout = 0
.ReadTotalTimeoutMultiplier = 0
.ReadTotalTimeoutConstant = miTimeout
.WriteTotalTimeoutMultiplier = 10
.WriteTotalTimeoutConstant = 100
End With
SetCommTimeouts(mhRS, uCtm)
End If
End Sub
Private Sub pDispose() Implements IDisposable.Dispose

If (Not mbDisposed AndAlso (mhRS.ToInt32 > 0)) Then
Try
Me.Close()
Finally
mbDisposed = True
GC.SuppressFinalize(Me)
End Try
End If


End Sub
Private Sub pEventsWatcher()

'Events to watch
Dim lMask As EventMasks = EventMasks.Break Or EventMasks.CarrierDetect Or EventMasks.ClearToSend Or _
EventMasks.DataSetReady Or EventMasks.Ring Or EventMasks.RxChar Or EventMasks.RXFlag Or _
EventMasks.StatusError
Dim iBytesRead, iTotBytes, iErrMask As Int32, aBuf As New ArrayList
Dim uComStat As COMSTAT
'-----------------------------------
' Creates Event
muOvlE = New OVERLAPPED
Dim hOvlE As GCHandle = GCHandle.Alloc(muOvlE, GCHandleType.Pinned)
muOvlE.hEvent = CreateEvent(Nothing, 1, 0, Nothing)
If muOvlE.hEvent.ToInt32 = 0 Then Throw New ApplicationException("Error creating event for overlapped reading")
'// Set mask
SetCommMask(mhRS, lMask)
'// Looks for RxChar
While mbEnableEvents = True
WaitCommEvent(mhRS, lMask, muOvlE)
Select Case WaitForSingleObject(muOvlE.hEvent, INFINITE)
Case WAIT_OBJECT_0
'// Event (or abort) detected
If mbEnableEvents = False Then Exit While
If (lMask And EventMasks.RxChar) > 0 Then
'// Read incoming data
ClearCommError(mhRS, iErrMask, uComStat)
If iErrMask = 0 Then
Dim ovl As New OVERLAPPED
Dim hOvl As GCHandle = GCHandle.Alloc(ovl, GCHandleType.Pinned)
ReDim mabtRxBuf(uComStat.cbInQue - 1)
If ReadFile(mhRS, mabtRxBuf, uComStat.cbInQue, iBytesRead, ovl) > 0 Then
If iBytesRead > 0 Then
'// Some bytes read, fills temporary buffer
If iTotBytes < miBufThreshold Then
aBuf.AddRange(mabtRxBuf)
iTotBytes += iBytesRead
End If
'// Threshold reached?, raises event
If iTotBytes >= miBufThreshold Then
'//Copies temp buffer into Rx buffer
ReDim mabtRxBuf(iTotBytes - 1)
aBuf.CopyTo(mabtRxBuf)
'// Raises event
Try
Me.OnCommEventReceived(Me, lMask)
Finally
iTotBytes = 0
aBuf.Clear()
End Try
End If
End If
End If
If (hOvl.IsAllocated) Then hOvl.Free()
End If
Else
'// Simply raises OnCommEventHandler event
Me.OnCommEventReceived(Me, lMask)
End If
Case Else
Dim sErr As String = New Win32Exception().Message
Throw New ApplicationException(sErr)
End Select
End While
'// Release Event Handle
CloseHandle(muOvlE.hEvent)
muOvlE.hEvent = IntPtr.Zero
If (hOvlE.IsAllocated) Then hOvlE.Free()
muOvlE = Nothing
End Sub



#End Region
回复
qshurufa 2009-07-14
关注!!
回复
ineedchrist 2009-07-14
        '检测端口状态
Public Function CheckCom(ByVal CommID As Integer) As Boolean
Try
Dim iMode As Int32 = Convert.ToInt32(IIf(meMode = Mode.Overlapped, FILE_FLAG_OVERLAPPED, 0))
mhRS = CreateFile("\\.\COM" & CommID.ToString, GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_EXISTING, iMode, 0)
If (mhRS.ToInt32 > 0) Then
Return True
Else
Return False
End If
Catch ex As Exception
SysLog("CommPort-CheckCom出现异常:" + ex.Message)
Return False
End Try
End Function
'初始化,并打开端口
Public Function Open() As Boolean
'// 以当前数据更新设备数据块
Dim uDcb As DCB, iRc As Int32
'// 设置工作模式
meMode = Mode.Overlapped
Dim iMode As Int32 = Convert.ToInt32(IIf(meMode = Mode.Overlapped, FILE_FLAG_OVERLAPPED, 0))
'// 初始化端口

Try
'// 创建当前COM口数据流句柄
mhRS = CreateFile("\\.\COM" & miPort.ToString, GENERIC_READ Or GENERIC_WRITE, 0, 0, OPEN_EXISTING, iMode, 0)
If (mhRS.ToInt32 > 0) Then
'// 清除所有错误
Dim lpErrCode As Int32
iRc = ClearCommError(mhRS, lpErrCode, New COMSTAT)
'// 清除 I/O 缓冲区
iRc = PurgeComm(mhRS, PurgeBuffers.RXClear Or PurgeBuffers.TxClear)
'// 得到COM设置
iRc = GetCommState(mhRS, uDcb)
'// 更新设置
Dim sParity As String = "NOEM"
sParity = sParity.Substring(meParity, 1)
'// 设置串口设备数据块状态
Dim sDCBState As String = String.Format("baud={0} parity={1} data={2} stop={3}", miBaudRate, sParity, miDataBit, CInt(meStopBit))
iRc = BuildCommDCB(sDCBState, uDcb)
uDcb.Parity = CByte(meParity)
'// 设置Xon/Xoff(发送机)状态
If mbUseXonXoff Then
uDcb.Bits1 = 768
Else
uDcb.Bits1 = 0
End If
iRc = SetCommState(mhRS, uDcb)
If iRc = 0 Then
Dim sErrTxt As String = New Win32Exception().Message
Throw New CIOChannelException("Unable to set COM state " & sErrTxt)
End If
'// 缓冲 (Rx,Tx)会话模式
iRc = SetupComm(mhRS, miBufferSize, miBufferSize)
'// 设置超时
pSetTimeout()
'//触发事件
If mbEnableEvents Then Me.EnableEvents()
Return True
Else
Return False
End If
Catch Ex As Exception
'一般性错误
SysLog("CommPort-Open出现异常:" + Ex.Message)
Return False
End Try
End Function
'关闭端口
Public Sub Close()
Try
If mhRS.ToInt32 > 0 Then
If mbEnableEvents = True Then
Me.DisableEvents()
End If
Dim ret As Boolean = CloseHandle(mhRS)
If Not ret Then Throw New Win32Exception
mhRS = New IntPtr(0)
End If
Catch ex As Exception
SysLog("CommPort-Close出现异常:" + ex.Message)
End Try

End Sub
'返回串口状态
ReadOnly Property IsOpen() As Boolean
Get
Return CBool(mhRS.ToInt32 > 0)
End Get
End Property
'写数据
Private Sub WriteValue(ByVal Buffer As Byte())
Dim iRc, iBytesWritten As Integer, hOvl As GCHandle
'-----------------------------------------------------------------
muOvlW = New OVERLAPPED
If mhRS.ToInt32 <= 0 Then
Throw New ApplicationException("Please initialize and open port before using this method")
Else
'// 创建事件
Try
hOvl = GCHandle.Alloc(muOvlW, GCHandleType.Pinned)
muOvlW.hEvent = CreateEvent(Nothing, 1, 0, Nothing)
If muOvlW.hEvent.ToInt32 = 0 Then Throw New ApplicationException("Error creating event for overlapped writing")
'// 清除 IO 缓冲区,并发送数据
iRc = WriteFile(mhRS, Buffer, Buffer.Length, 0, muOvlW)
If iRc = 0 Then
If Marshal.GetLastWin32Error <> ERROR_IO_PENDING Then
Throw New ApplicationException("Write command error")
Else
'Tx
If GetOverlappedResult(mhRS, muOvlW, iBytesWritten, 1) = 0 Then
Throw New ApplicationException("Write pending error")
Else
'//是否发送所有数据
If iBytesWritten <> Buffer.Length Then Throw New ApplicationException("Write Error - Bytes Written " & iBytesWritten.ToString & " of " & Buffer.Length.ToString)
End If
End If
End If
Catch ex As Exception
SysLog("CommPort-WriteValue出现异常:" + ex.Message)
Finally
'关闭句柄
CloseHandle(muOvlW.hEvent)
If (hOvl.IsAllocated = True) Then hOvl.Free()
End Try
End If
End Sub
'写数据
'isHex:是否以十六进制发送,默认以十六进制发送
Sub SendCommand(ByVal Buffer As String, Optional ByVal meWriteMode As WriteMode = WriteMode.HexData)
Dim oEncoder As New System.Text.ASCIIEncoding
Dim oEnc As Encoding = Encoding.GetEncoding(1252)
'-------------------------------------------------------------
Dim aByte() As Byte
Dim i As Integer
Try
If meWriteMode = WriteMode.HexData Then
i = Buffer.Length / 2 - 1
ReDim aByte(i)
For i = 0 To i
aByte(i) = "&H" & Mid(Buffer, i * 2 + 1, 2)
Next
Else
aByte = oEnc.GetBytes(Buffer)
End If
Me.WriteValue(aByte)
Catch ex As Exception
SysLog("CommPort-SendCommand出现异常:" + ex.Message)
End Try
End Sub

'读数据,返回长度
Public Function Read(ByVal Bytes2Read As Integer) As Integer
Dim iReadChars, iRc As Integer, hOvl As GCHandle
If Bytes2Read = 0 Then Bytes2Read = miBufferSize
muOvlR = New OVERLAPPED
If mhRS.ToInt32 <= 0 Then
Throw New ApplicationException("使用该方法前需要初始化并打开串口")
Else
'得到字节
Try
GCHandle.Alloc(muOvlR, GCHandleType.Pinned)
muOvlR.hEvent = CreateEvent(Nothing, 1, 0, Nothing)
If muOvlR.hEvent.ToInt32 = 0 Then Throw New ApplicationException("重置事件失败")
'清除 IO缓冲区并且读出数据
ReDim mabtRxBuf(Bytes2Read - 1)
iRc = ReadFile(mhRS, mabtRxBuf, Bytes2Read, iReadChars, muOvlR)
If iRc = 0 Then
If Marshal.GetLastWin32Error() <> ERROR_IO_PENDING Then
Throw New ApplicationException("读失败")
Else
'待复制的字符
iRc = WaitForSingleObject(muOvlR.hEvent, miTimeout)
Select Case iRc
Case WAIT_OBJECT_0
'得到数据……
If GetOverlappedResult(mhRS, muOvlR, iReadChars, 0) = 0 Then
Throw New ApplicationException("读失败")
Else
Return iReadChars
End If
Case WAIT_TIMEOUT
Throw New IOTimeoutException("读超时")
Case Else
Throw New ApplicationException("其它未知读错误")
End Select
End If
Else
Return (iReadChars)
End If
Catch ex As Exception
SysLog("CommPort-SendCommand出现异常:" + ex.Message)
Finally
'关闭
CloseHandle(muOvlR.hEvent)
If (hOvl.IsAllocated) Then hOvl.Free()
End Try
End If
End Function
回复
ineedchrist 2009-07-14
#Region "Win32API"
'// Win32 API
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetCommState(ByVal hCommDev As IntPtr, ByRef lpDCB As DCB) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function GetCommState(ByVal hCommDev As IntPtr, ByRef lpDCB As DCB) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function BuildCommDCB(ByVal lpDef As String, ByRef lpDCB As DCB) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetupComm(ByVal hFile As IntPtr, ByVal dwInQueue As Int32, ByVal dwOutQueue As Int32) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetCommTimeouts(ByVal hFile As IntPtr, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function GetCommTimeouts(ByVal hFile As IntPtr, ByRef lpCommTimeouts As COMMTIMEOUTS) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function ClearCommError(ByVal hFile As IntPtr, ByRef lpErrors As Int32, ByRef lpComStat As COMSTAT) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function PurgeComm(ByVal hFile As IntPtr, ByVal dwFlags As Int32) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function EscapeCommFunction(ByVal hFile As IntPtr, ByVal ifunc As Int32) As Boolean
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function WaitCommEvent(ByVal hFile As IntPtr, ByRef Mask As EventMasks, ByRef lpOverlap As OVERLAPPED) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function WriteFile(ByVal hFile As IntPtr, ByVal Buffer As Byte(), ByVal nNumberOfBytesToWrite As Integer, ByRef lpNumberOfBytesWritten As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function ReadFile(ByVal hFile As IntPtr, <Out()> ByVal Buffer As Byte(), ByVal nNumberOfBytesToRead As Integer, ByRef lpNumberOfBytesRead As Integer, ByRef lpOverlapped As OVERLAPPED) As Integer
End Function
<DllImport("kernel32.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CreateFile(ByVal lpFileName As String, ByVal dwDesiredAccess As Integer, ByVal dwShareMode As Integer, ByVal lpSecurityAttributes As Integer, ByVal dwCreationDisposition As Integer, ByVal dwFlagsAndAttributes As Integer, ByVal hTemplateFile As Integer) As IntPtr
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function CloseHandle(ByVal hObject As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Public Shared Function GetCommModemStatus(ByVal hFile As IntPtr, ByRef lpModemStatus As Int32) As Boolean
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetEvent(ByVal hEvent As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function CreateEvent(ByVal lpEventAttributes As IntPtr, ByVal bManualReset As Int32, ByVal bInitialState As Int32, ByVal lpName As String) As IntPtr
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function WaitForSingleObject(ByVal hHandle As IntPtr, ByVal dwMilliseconds As Int32) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function GetOverlappedResult(ByVal hFile As IntPtr, ByRef lpOverlapped As OVERLAPPED, ByRef lpNumberOfBytesTransferred As Int32, ByVal bWait As Int32) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetCommMask(ByVal hFile As IntPtr, ByVal lpEvtMask As Int32) As Int32
End Function
<DllImport("kernel32.dll", SetlastError:=True, CharSet:=CharSet.Auto)> Private Shared Function GetDefaultCommConfig(ByVal lpszName As String, ByRef lpCC As COMMCONFIG, ByRef lpdwSize As Integer) As Boolean
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function SetCommBreak(ByVal hFile As IntPtr) As Boolean
End Function
<DllImport("kernel32.dll", SetlastError:=True)> Private Shared Function ClearCommBreak(ByVal hFile As IntPtr) As Boolean
End Function


#End Region

#Region "事件"
Public Event CommEvent As CommEventHandler
#End Region

#Region "委托"
Public Delegate Sub CommEventHandler(ByVal source As CommPort, ByVal Mask As EventMasks)
#End Region

#Region "属性"
Public Property Port() As Integer
Get
Return miPort
End Get
Set(ByVal Value As Integer)
miPort = Value
End Set
End Property
'清理通信缓冲区
Public Sub PurgeBuffer(ByVal Mode As PurgeBuffers)
If (mhRS.ToInt32 > 0) Then PurgeComm(mhRS, Mode)
End Sub
Public Overridable Property Timeout() As Integer
Get
Return miTimeout
End Get
Set(ByVal Value As Integer)
miTimeout = CInt(IIf(Value = 0, 500, Value))
'//如果端口打开,更改状态为忙
pSetTimeout()
End Set
End Property
'端口的奇偶
Public Property Parity() As DataParity
Get
Return meParity
End Get
Set(ByVal Value As DataParity)
meParity = Value
End Set
End Property
'停止位
Public Property StopBit() As DataStopBit
Get
Return meStopBit
End Get
Set(ByVal Value As DataStopBit)
meStopBit = Value
End Set
End Property
'波特率
Public Property BaudRate() As Integer
Get
Return miBaudRate
End Get
Set(ByVal Value As Integer)
miBaudRate = Value
End Set
End Property
'数据位
Public Property DataBit() As Integer
Get
Return miDataBit
End Get
Set(ByVal Value As Integer)
miDataBit = Value
End Set
End Property
'得到缓冲区大小
Public Property BufferSize() As Integer
Get
Return miBufferSize
End Get
Set(ByVal Value As Integer)
miBufferSize = Value
End Set
End Property
#End Region
回复
ineedchrist 2009-07-14
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
''''命名空间:JustinIO
''''类名:  CommPort
''''类说明: 考虑到标准组件操控性能不强,因此利用API对RS232通讯全封装
''''作者: Cong Wenchao
''''时间: 2007,11,3
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Imports System
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.Threading
Imports System.ComponentModel
Imports System.IO
Namespace JustinIO
#Region "CommPort"
Public Class CommPort : Implements IDisposable

#Region "类成员"
Private mhRS As IntPtr = New IntPtr(0) 'COM句柄
Private miPort As Integer = 1 '默认打开COM1
Private miTimeout As Int32 = 70 '超时设置
Private miBaudRate As Int32 = 115200
Private meParity As DataParity = 0
Private meStopBit As DataStopBit = 0
Private miDataBit As Int32 = 8
Private miBufferSize As Int32 = 512 '缓冲区大小
Private mabtRxBuf As Byte() '返回缓冲区数值
Private meMode As Mode '工作模式
Private moEvents As Thread
Private mbDisposed As Boolean
Private mbUseXonXoff As Boolean
Private mbEnableEvents As Boolean
Private miBufThreshold As Int32 = 1
Private muOvlE As OVERLAPPED
Private muOvlW As OVERLAPPED
Private muOvlR As OVERLAPPED
#End Region

#Region "Enums"
'奇偶值
Public Enum DataParity
Parity_None = 0
Parity_Odd
Parity_Even
Parity_Mark
End Enum
'停止位
Public Enum DataStopBit
StopBit_1 = 1
StopBit_2
End Enum
'清理缓冲区
<Flags()> Public Enum PurgeBuffers
RXAbort = &H2
RXClear = &H8
TxAbort = &H1
TxClear = &H4
End Enum
Private Enum Lines
SetRts = 3
ClearRts = 4
SetDtr = 5
ClearDtr = 6
ResetDev = 7 '如果可能的话,重启
SetBreak = 8 '设置中断
ClearBreak = 9 '清除中断
End Enum
'状态
<Flags()> Public Enum ModemStatusBits
ClearToSendOn = &H10
DataSetReadyOn = &H20
RingIndicatorOn = &H40
CarrierDetect = &H80
End Enum
'工作模式
Public Enum Mode
NonOverlapped
Overlapped
End Enum
'事件枚举
<Flags()> Public Enum EventMasks
RxChar = &H1
RXFlag = &H2
TxBufferEmpty = &H4
ClearToSend = &H8
DataSetReady = &H10
CarrierDetect = &H20
Break = &H40
StatusError = &H80
Ring = &H100
End Enum
'写数据的模式
Public Enum WriteMode
HexData = 0
DecimalData = 1
End Enum
#End Region

#Region "结构体"
<StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure DCB
Public DCBlength As Int32
Public BaudRate As Int32
Public Bits1 As Int32
Public wReserved As Int16
Public XonLim As Int16
Public XoffLim As Int16
Public ByteSize As Byte
Public Parity As Byte
Public StopBits As Byte
Public XonChar As Char
Public XoffChar As Char
Public ErrorChar As Char
Public EofChar As Char
Public EvtChar As Char
Public wReserved2 As Int16
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure COMMTIMEOUTS
Public ReadIntervalTimeout As Int32
Public ReadTotalTimeoutMultiplier As Int32
Public ReadTotalTimeoutConstant As Int32
Public WriteTotalTimeoutMultiplier As Int32
Public WriteTotalTimeoutConstant As Int32
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=8)> Private Structure COMMCONFIG
Public dwSize As Int32
Public wVersion As Int16
Public wReserved As Int16
Public dcbx As DCB
Public dwProviderSubType As Int32
Public dwProviderOffset As Int32
Public dwProviderSize As Int32
Public wcProviderData As Int16
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> Public Structure OVERLAPPED
Public Internal As Int32
Public InternalHigh As Int32
Public Offset As Int32
Public OffsetHigh As Int32
Public hEvent As IntPtr
End Structure
<StructLayout(LayoutKind.Sequential, Pack:=1)> Private Structure COMSTAT
Dim fBitFields As Int32
Dim cbInQue As Int32
Dim cbOutQue As Int32
End Structure

#End Region

#Region "常量"
Private Const PURGE_RXABORT As Integer = &H2
Private Const PURGE_RXCLEAR As Integer = &H8
Private Const PURGE_TXABORT As Integer = &H1
Private Const PURGE_TXCLEAR As Integer = &H4
Private Const GENERIC_READ As Integer = &H80000000
Private Const GENERIC_WRITE As Integer = &H40000000
Private Const OPEN_EXISTING As Integer = 3
Private Const INVALID_HANDLE_VALUE As Integer = -1
Private Const IO_BUFFER_SIZE As Integer = 1024
Private Const FILE_FLAG_OVERLAPPED As Int32 = &H40000000
Private Const ERROR_IO_PENDING As Int32 = 997
Private Const WAIT_OBJECT_0 As Int32 = 0
Private Const ERROR_IO_INCOMPLETE As Int32 = 996
Private Const WAIT_TIMEOUT As Int32 = &H102&
Private Const INFINITE As Int32 = &HFFFFFFFF
#End Region
回复
古今多少事 2009-07-13
学习!
回复
yoha123 2009-07-13
还是不可以显示汉字,只是显示"???????????"
回复
zdingyun 2008-12-27
醒目网石 www.xmnetstone.com
请楼主到上述网址下载VB.NET2005编写的串口例程工程.
就如1楼所说的Encoding.Default.GetString() 转回汉字
Public Class Form1

Dim buffB(30) As Byte '串口接收缓冲区 如果接收字符很长最好设的大点

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

SerialPort1.BaudRate = 9600 '波特率设为9600
SerialPort1.PortName = "com1" '端口为串口1

If SerialPort1.IsOpen = False Then SerialPort1.Open() '打开串口
End Sub

Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
SerialPort1.Read(buffB, 0, 30)
BeginInvoke(New EventHandler(AddressOf ONMLoadA), SerialPort1.BytesToRead()) '使用委托方式显示接收到的字符串
End Sub

Sub ONMLoadA(ByVal sender As System.Object, ByVal e As System.EventArgs)
'TextBox1.Text = Encoding.ASCII.GetString(buffB, 0, 30) '显示ASCII单字节字符
TextBox1.Text = Encoding.Default.GetString(buffB, 0, 30) '显示汉字
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
SerialPort1.Write("test") '发送字符串
End Sub
End Class

上述是窗体中的主代码.
Encoding估计是一个对象,那个工程中有.
回复
人王 2008-12-26
利用 System.Text.Encoding.Default.GetBytes() 把字符串转换成byte数组在发送,收到是在利用System.Text.Encoding.Default.GetString() 转回来
回复
相关推荐
发帖
VB
创建于2007-09-28

1.6w+

社区成员

VB技术相关讨论,主要为经典vb,即VB6.0
申请成为版主
帖子事件
创建了帖子
2008-12-26 07:59
社区公告
暂无公告