Public Class Form1
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
InitializeComponent()
'Add any initialization after the InitializeComponent() call
End Sub
'Form overrides dispose to clean up the component list.
Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
If disposing Then
If Not (components Is Nothing) Then
components.Dispose()
End If
End If
MyBase.Dispose(disposing)
End Sub
'Required by the Windows Form Designer
Private components As System.ComponentModel.IContainer
'NOTE: The following procedure is required by the Windows Form Designer
'It can be modified using the Windows Form Designer.
'Do not modify it using the code editor.
Friend WithEvents open_com2 As System.Windows.Forms.Button
<System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
Me.open_com2 = New System.Windows.Forms.Button
Me.SuspendLayout()
'
'open_com2
'
Me.open_com2.Location = New System.Drawing.Point(56, 88)
Me.open_com2.Name = "open_com2"
Me.open_com2.Size = New System.Drawing.Size(184, 64)
Me.open_com2.TabIndex = 0
Me.open_com2.Text = "Open Com2"
'
'Form1
'
Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
Me.ClientSize = New System.Drawing.Size(292, 266)
Me.Controls.Add(Me.open_com2)
Me.Name = "Form1"
Me.Text = "Form1"
Me.ResumeLayout(False)
End Sub
#End Region
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles open_com2.Click
'usually, you would declare the serial port at form level and initialize
'it in the constructor so you can get responses from the port
'declare the serial port and set it for 4800,N,8,1
Dim serial As New IO.Ports.SerialPort("COM2")
serial.BaudRate = 4800
serial.Parity = IO.Ports.Parity.None
serial.DataBits = 8
serial.StopBits = IO.Ports.StopBits.One
'make sure the port is open
Try
If Not serial.IsOpen Then serial.Open()
Catch ex As Exception
'specifically an UnauthorizedAccessException
'the port is already open somewhere else
MessageBox.Show("The port is already opened by another process.")
Exit Sub
End Try
'
'uncomment the next line if you do not need to get responses
'and you are done with the port
'serial.Close()
End Sub
End Class
'