Public Class Form1
Dim msg As String
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
With SerialPort1
If .IsOpen = True Then .Close()
End With
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub search()
Dim s As String = ""
Dim ma As Byte = My.Computer.Ports.SerialPortNames.Count - 1
ComboBox1.Items.Clear()
For i As Byte = 0 To ma
s = My.Computer.Ports.SerialPortNames(i).ToString
If InStr(s, "i") = 0 Then
ComboBox1.Items.Add(s)
End If
Next
ma = ComboBox1.Items.Count
If ma > 0 Then
ComboBox1.SelectedIndex = ma - 1
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
search()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If ComboBox1.Text <> "" Or InStr(ComboBox1.Text, "m") = 0 Then
With SerialPort1
Try
If .IsOpen = True Then .Close()
Catch ex As Exception
MsgBox("Error 1", MsgBoxStyle.Information, "Error")
Exit Sub
End Try
.DataBits = 8
.BaudRate = 4800
.StopBits = IO.Ports.StopBits.One
.Parity = IO.Ports.Parity.None
.Handshake = IO.Ports.Handshake.None
.PortName = ComboBox1.Text
AddHandler SerialPort1.DataReceived, AddressOf SerialPort1_DataReceived
Try
.Open()
Catch ex As Exception
MsgBox(Err.Description, MsgBoxStyle.Information, "Error")
Me.Show()
Exit Sub
End Try
MsgBox("Connected")
End With
End If
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
Try
msg = msg & SerialPort1.ReadExisting
Me.Invoke(New EventHandler(AddressOf baby))
Catch ex As Exception
End Try
End Sub
Private Sub baby()
If InStr(msg, "OK") > 0 Then
ListBox1.Items.Add(msg)
msg = ""
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
With SerialPort1
Try
If .IsOpen = True Then .Close()
Catch ex As Exception
MsgBox("Error 2", MsgBoxStyle.Information, "Error")
Exit Sub
End Try
End With
End Sub
End Class