VB采用SerialPort控件串口通信中,接受数据怎么实现?

这是写了的部分
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Dim n As Integer
Dim rxdata(2) As Byte
SerialPort1.PortName = "COM9"
n = Me.SerialPort1.BytesToRead '接收到的字节数
If (n > 0) Then ReDim rxdata(n - 1)
Me.SerialPort1.Read(rxdata, 0, n)
SerialPort1.Close()
End Sub

在Form_Load()内写入以下代码,进行串口初始化

MSComm1.CommPort =9 '读取com口号
If MSComm1.PortOpen = True Then '如果串口打开先关闭后再进行其他操作
MSComm1.PortOpen = False
End If
MSComm1.PortOpen = True '打开串口9

在退出按钮中写入
MSComm1.PortOpen = False '以在退出程序时关闭串口

双击串口控件图标,在其处理程序中写入以下代码
Dim BytReceived() As Byte
Dim strBuff As String
Dim i As Integer
Select Case MSComm1.CommEvent '事件发生
Case 2
MSComm1.InputLen = 0 '读入缓冲区全部内容
strBuff = MSComm1.Input '读入到缓冲区,strBuff 中存放的就是串口接收的数据
End Select
End Sub

满意请及时采纳,谢谢追问

非常谢谢您这么详细的答案,但是我的VS 2012上是没有MScomm控件的,只能采用SerialPort进行控制啊!

追答

找找看,我机器里没安装VS2012

温馨提示:内容为网友见解,仅供参考
第1个回答  推荐于2017-09-14
做RS232 通讯 用SerialPort1控件 就可以了啊
我用虚拟串口 做测试,
写入 SerialPort1.Write("字符串数据")
读取 SerialPort2.ReadExisting.ToString

记得给两个控件附上必要的属性如COM口,并打开。
读取时,可以使用SerialPort自带的事件,但是记得在事件所调用的方法里尽量使用委托的方式抓取其他控件的句柄。
相似回答