向您请教关于SerialPort(vb.net)使用问题!
发布网友
发布时间:2022-05-04 01:24
我来回答
共2个回答
热心网友
时间:2022-06-20 10:00
SerialPort是用于串口通信的控件与VB6中的MSCOMM控件相似,使用很方便,多查看MSDN上的帮助也可以去网上找一下相关的例程。
热心网友
时间:2022-06-20 10:00
vb.net Code
Imports System.IO.Ports
Imports System.Text
Public Class Form1
Dim RS232Com As New SerialPort
Dim mPortName As String
Public Sub OpenCOM()
mPortName = Me.CmbCom.SelectedItem.ToString
RS232Com = New SerialPort(mPortName, 9600, Parity.None, 8, StopBits.One)
RS232Com.Encoding = Encoding.ASCII
If Not RS232Com.IsOpen Then RS232Com.Open()
End Sub
Public Sub CloseCOM()
If RS232Com.IsOpen Then RS232Com.Close()
End Sub
Private Sub BtnOpen_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnOpen.Click
Call OpenCOM()
End Sub
Private Sub BtnClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClose.Click
Call CloseCOM()
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For Each sp As String In SerialPort.GetPortNames
Me.CmbCom.Items.Add(sp)
Next
Me.CmbCom.SelectedIndex = 0
End Sub
Private Sub BtnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSend.Click
RS232Com.Write(Me.TextBox1.Text) '即写命令过去
End Sub
Private Sub BtnReceived_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnReceived.Click
Dim sOut As String
sOut = RS232Com.ReadExisting 'sOut即读到的字符串
End Sub
End Class