1、在Form1的设计模式下添加以下控件:
2、添加好控件之后我们就可以打开Form1.vb进行编程了:
1 '使用串口需要引用的命名空间 2 Imports System.IO.Ports 3 Imports System 4 5 6 Public Class Form1 7 8 9 10 '在设计视图中双击Form1窗体出现的函数,在第一次显示窗体前发生的事件写在这个里面,类似于ViewWillAppear 11 Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 12 13 Dim ports As String() = SerialPort.GetPortNames() '必须用命名空间,用SerialPort,获取计算机的有效串口 14 15 Dim port As String 16 17 For Each port In ports 18 portnamebox.Items.Add(port) '向combobox中添加项 19 Next 20 21 '初始化界面 22 baudratebox.Text = baudratebox.Items(2) '注释和不注释的地方可以替换 23 portnamebox.Text = portnamebox.Items(0) 24 'baudratebox.SelectedIndex() = 2 25 ' portnamebox.SelectedIndex() = 0 26 Serial_Port1() '初始化串口 27 Label3.Text = SerialPort1.IsOpen 28 statuslabel.Text = "串口未连接" 29 statuslabel.ForeColor = Color.Red 30 sendbox.Text = "123" 31 receivebytes.Text = "0" 32 linecheck.Enabled = True 33 timebox.Enabled = True 34 35 '让发送、接收数据按钮不能点击(失能) 36 Button1.Enabled = False 37 Button2.Enabled = False 38 Button3.Enabled = False 39 40 41 42 43 End Sub 44 45 46 Private Sub Serial_Port1() '设置串口参数 47 'SerialPort1.BaudRate = Val(baudratebox.Text) '波特率 48 'SerialPort1.PortName = portnamebox.Text '串口名称 49 SerialPort1.PortName = portnamebox.SelectedItem 50 SerialPort1.BaudRate = Val(baudratebox.SelectedItem) 51 SerialPort1.DataBits = 8 '数据位 52 SerialPort1.StopBits = IO.Ports.StopBits.One '停止位 53 SerialPort1.Parity = IO.Ports.Parity.None '校验位 54 End Sub 55 56 57 '关闭串口连接 58 Private Sub closebtn_Click(ByVal sender