01.
Imports
System
02.
Imports
System.Threading
03.
Imports
System.IO.Ports
04.
Imports
System.ComponentModel
05.
06.
Public
Class
Form1
07.
08.
Dim
myPort
As
Array
09.
10.
Private
Sub
GetSerialPortNames()
11.
For
Each
sport
As
String
In
My.Computer.Ports.SerialPortNames
12.
portComboBox.Items.Add(sport)
13.
Next
14.
End
Sub
15.
16.
Private
Sub
Form1_Load(sender
As
Object
, e
As
EventArgs)
Handles
MyBase
.Load
17.
Dim
BaudRates()
As
String
= {
"300"
,
"1200"
,
"2400"
,
"4800"
,
"9600"
,
"14400"
,
"19200"
,
"28800"
,
"38400"
,
"57600"
,
"115200"
}
18.
baudComboBox.Items.AddRange(BaudRates)
19.
baudComboBox.SelectedIndex = 4
20.
Try
21.
GetSerialPortNames()
22.
baudComboBox.SelectedIndex = 0
23.
Catch
24.
MsgBox(
"No ports connected."
)
25.
End
Try
26.
Timer1.
Stop
()
27.
28.
End
Sub
29.
30.
Private
Sub
connectBotton_Click(sender
As
Object
, e
As
EventArgs)
Handles
connectBotton.Click
31.
SerialPort1.PortName = portComboBox.Text
32.
SerialPort1.BaudRate = baudComboBox.Text
33.
SerialPort1.DataBits = 8
34.
SerialPort1.StopBits = IO.Ports.StopBits.One
35.
SerialPort1.Parity = IO.Ports.Parity.None
36.
SerialPort1.Open()
37.
Timer1.Interval = 500
38.
Timer1.Start()
39.
portComboBox.Enabled =
False
40.
baudComboBox.Enabled =
False
41.
connectBotton.Enabled =
False
42.
disconnectBotton.Enabled =
True
43.
44.
End
Sub
45.
46.
Private
Sub
closeBotton_Click(sender
As
Object
, e
As
EventArgs)
Handles
disconnectBotton.Click
47.
48.
SerialPort1.Close()
49.
Timer1.
Stop
()
50.
portComboBox.Enabled =
True
51.
baudComboBox.Enabled =
True
52.
connectBotton.Enabled =
True
53.
disconnectBotton.Enabled =
False
54.
55.
End
Sub
56.
57.
Private
Sub
Form1_FormClosing(sender
As
Object
, e
As
FormClosingEventArgs)
Handles
MyBase
.FormClosing
58.
SerialPort1.Close()
59.
Timer1.
Stop
()
60.
portComboBox.Enabled =
True
61.
baudComboBox.Enabled =
True
62.
connectBotton.Enabled =
True
63.
disconnectBotton.Enabled =
False
64.
End
65.
66.
End
Sub
67.
68.
Delegate
Sub
myMethodDelegate(
ByVal
[text]
As
String
)
69.
Dim
myDelegate
As
New
myMethodDelegate(
AddressOf
ShowString)
70.
71.
Private
Sub
SerialPort_DataReceived(
ByVal
sender
As
Object
,
ByVal
e
As
System.IO.Ports.SerialDataReceivedEventArgs)
Handles
SerialPort1.DataReceived
72.
Dim
str
As
String
= SerialPort1.ReadExisting()
73.
Invoke(myDelegate, str)
74.
End
Sub
75.
76.
Sub
ShowString(
ByVal
myString
As
String
)
77.
outputTextBox.AppendText(myString)
78.
End
Sub
79.
80.
Private
Sub
Button1_Click(sender
As
Object
, e
As
EventArgs)
Handles
Button1.Click
81.
outputTextBox.Clear()
82.
End
Sub
83.
End
Class