Stap 3: programmeren
Wij programmeren nu alle onderdelen van het formulier. Eerste formuliercode belasting. Om te doen dus tweemaal klikken in om het even welk waar in het formulier en de code wijzigen om te
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load GetSerialPortNames() End Sub
Voeg vervolgens enkele aanvullende code boven de Form1_Load wetboek te halen uw comm-poort en een functie om te werken met uw 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
En onder de code van 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