Imports System.IO.PortsPublic Class Form1 Dim WithEvents SerialPort1 As New SerialPort() Private Sub BtnOpenPort_Click(sender As Object, e As EventArgs) Handles BtnOpenPort.Click Try If Not SerialPort1.IsOpen Then SerialPort1.PortName = "COM4" ' Change to your COM port SerialPort1.BaudRate = 57600 SerialPort1.Parity = Parity.Even SerialPort1.DataBits = 7 SerialPort1.StopBits = StopBits.Two SerialPort1.Open() ' Clear buffers immediately after opening SerialPort1.DiscardInBuffer() SerialPort1.DiscardOutBuffer() MessageBox.Show("COM Port Opened") Else MessageBox.Show("COM Port is already open") End If Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End Try End Sub Private Sub BtnClosePort_Click(sender As Object, e As EventArgs) Handles BtnClosePort.Click Try If SerialPort1.IsOpen Then ' Clear buffers before closing SerialPort1.DiscardInBuffer() SerialPort1.DiscardOutBuffer() SerialPort1.Close() MessageBox.Show("COM Port Closed") Else MessageBox.Show("COM Port is already closed") End If Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End Try End SubEnd Class
Private Sub BtnOpenPort_Click(sender As Object, e As EventArgs) Handles BtnOpenPort.Click Try OmronSerialHostLinkCom1.InitializeComs() System.Threading.Thread.Sleep(1000) OmronSerialHostLinkCom1.DisableSubscriptions = 0 Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End TryEnd Sub Private Sub BtnClosePort_Click(sender As Object, e As EventArgs) Handles BtnClosePort.Click Try OmronSerialHostLinkCom1.DisableSubscriptions = 1 System.Threading.Thread.Sleep(1000) OmronSerialHostLinkCom1.closeComm() Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End Try End Sub
Code: [Select]Private Sub BtnOpenPort_Click(sender As Object, e As EventArgs) Handles BtnOpenPort.Click Try OmronSerialHostLinkCom1.InitializeComs() System.Threading.Thread.Sleep(1000) OmronSerialHostLinkCom1.DisableSubscriptions = 0 Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End TryEnd Sub Private Sub BtnClosePort_Click(sender As Object, e As EventArgs) Handles BtnClosePort.Click Try OmronSerialHostLinkCom1.DisableSubscriptions = 1 System.Threading.Thread.Sleep(1000) OmronSerialHostLinkCom1.closeComm() Catch ex As Exception MessageBox.Show("Error: " & ex.Message) End Try End Sub