Serial Port component from Visual Basic 6 to .NET Framework

977 Views Asked by At

So, I'm trying to port a Visual Basic 6 software into the new dot NET.

My software is using the serial port via the code

My_form.Ser_port.Settings = "38400,n,8,1"
My_form.Ser_port.RThreshold = 1
If My_form.Ser_port.PortOpen = False Then
    My_form.Ser_port.PortOpen = True
End If

Clearly, it seems that dot NET doesn't have such settings.

I have correctly imported the SerialPort1 componetn and I can see it on the bottom of my working area but, how can I open/Close and set the parameters as VB6? I see I can set the BaudRate, RecievedByesThreshold but there's no PortOpen option.

Does it opens automatically?

1

There are 1 best solutions below

0
robopavlik On

In your code (VB6) SerialPort.PortOpen is a property:

SerialPort.PortOpen=True or False

But in VB.NET it is not property, it is a sub of the component:

You have to call SerialPort.Open() or SerialPort.Close(). You can also get property if it's port open or no: SerialPort.IsOpen=True or False.

Here is an example how to work with serial port in VB.Net. If you worked with VS2022 you have to first install NuGet Package named System.IO.Ports.

Public Class Form1
Dim SP As New System.IO.Ports.SerialPort
Sub New()
    ' This call is required by the designer.
    InitializeComponent()
    ' Add any initialization after the InitializeComponent() call.
    With SP
        .PortName = "COM1" 
        .BaudRate = 1200
        .Parity = IO.Ports.Parity.None
        .DataBits = 8
        .StopBits = 1
    End With
  End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If SP.IsOpen Then
Exit Sub
Else
SP.Open()
End If
End Sub
Private Sub Form1_Closing(sender As Object, e As EventArgs) Handles MyBase.Closing
If SP.IsOpen Then
SP.Close()
End If
End Sub
End Class