VB2008的串口枚举

来源:互联网 发布:修改服务器端口 编辑:程序博客网 时间:2024/04/30 00:39

VB2008的串口枚举


要求自动枚举存在的串口,并将其打印到下拉列表中,并尝试打开和关闭串口

一. 准备控件

1. 串口控件: Serialport

2. 下拉列表:CommBox

3. 显示状态的标签:State_Label


二. 枚举"函数"


'检测有用的串口    Private Sub init_comm()        '使用系统枚举串口        Dim ports As String() = IO.Ports.SerialPort.GetPortNames()        Comm_Box.Items.Clear()      '清Comm的items        '将枚举到的串口添加到Comm控件        Dim port As String        For Each port In ports            Comm_Box.Items.Add(port)        Next port        '将枚举到的第一个串口显示出来        If Comm_Box.Items.Count Then            Comm_Box.Text = Comm_Box.Items.Item(0)        End If    End Sub

三.尝试打开串口

可能已有的串口被占用,打开前需要先尝试一下:

If Comm_Box.Items.Count Then    '判断是否枚举到串口            SerialPort.PortName = Comm_Box.Text            Try                SerialPort.Open() '打开串口                If SerialPort.IsOpen = True Then                    '连接指示                    State_Label.Text = "串口已连接"                    State_Label.ForeColor = Drawing.Color.Green                End If            Catch ex As Exception                MessageBox.Show(ex.Message)            End Try        Else            MsgBox("未发现任何有效串口,请接入串口后重试!", MsgBoxStyle.OkOnly)            init_comm()                     '再次枚举一下串口        End If


四. 尝试关闭串口

Try            SerialPort.Close() '关闭串口            If SerialPort.IsOpen = False Then                '指示连接断开                State_Label.Text = "串口未连接"                State_Label.ForeColor = Drawing.Color.Red            End If        Catch ex As Exception            MessageBox.Show(ex.Message)        End Try



原创粉丝点击