Paso 3: programación
Ahora programamos todos los componentes de la forma. Primer código de carga del formulario. Así que haga doble clic en cualquiera donde en el formulario y cambiar el código para
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load GetSerialPortNames() End Sub
Añadir un código adicional sobre el código de Form1_Load para obtener su puerto comm y alguna función para trabajar con el software
Imports System.IO Imports System.IO.Ports Imports System.Threading
Public Class Form1 Dim buffer As String Delegate Sub myMethodDelegate(ByVal [text] As String) Dim bD1 As New myMethodDelegate(AddressOf process) Dim WithEvents SerialPort As New IO.Ports.SerialPort
Private Sub Form1_Disposed(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Disposed If SerialPort.IsOpen() Then SerialPort.Close() End If End Sub
Y a continuación el código de Form1_Load
Sub GetSerialPortNames() For Each sp As String In My.Computer.Ports.SerialPortNames lstPorts.Items.Add(sp) Next End Sub
Sub SendSerialData(ByVal Port As String, ByVal data As String) If (SerialPort.IsOpen) Then SerialPort.Write(data) Else MsgBox("Not connected to Port.") End If End Sub
Sub process(ByVal myString As String) buffer = buffer + myString Dim str As String str = buffer If InStr(str, "|") Then Dim words As String() = str.Split(New Char() {"|"}) buffer = "" Dim word As String For Each word In words If (word.Length > 0) Then lstConsole.Items.Add(word) End If Next End If End Sub
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived Dim str As String = SerialPort.ReadExisting() Invoke(bD1, str) End Sub
Private Sub SerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived Dim str As String = SerialPort.ReadExisting() Invoke(bD1, str) End Sub