'Imports System.IO.Ports

Public Class Form1

    Shared ZSend As Short
    Shared MyArray() As Byte

    'SerialPort1.Read(EmpfU555, 0, 2)
    'U555Wert = BitConverter.ToUInt16(EmpfU555, 0)

    'Private Sub com_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs)
    'Dim data As Byte = CByte(SerialPort1.ReadByte())
    'Dim data As Byte = CByte(com.ReadByte())

    'Debug.Print(data)

    'End Sub

    Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs)

    End Sub

    Private Sub TextBox2_TextChanged(sender As System.Object, e As System.EventArgs)

    End Sub

    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click     'Connect-Button
        Try
            SerialPort1.PortName = TextBox1.Text
            SerialPort1.BaudRate = TextBox2.Text
            SerialPort1.Open()
            Button1.Enabled = False
            Button2.Enabled = True
            Button4.Enabled = True

        Catch ex As Exception
            MsgBox("Verbindung konnte nicht hergestellt werden!")
            SerialPort1.PortName = "COM1"
            SerialPort1.BaudRate = "9600"
        End Try
    End Sub


    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click     'Senden-Button
        TextBox3.Focus()                                                                                'Fokus wird auf TextBox3 gesetzt
        Try
            ZSend = CInt(TextBox3.Text)                                                               'Text in Integer umwandeln (CStr-Interger in Text)

            If ZSend > -1 And ZSend < 65535 Then
                MyArray = BitConverter.GetBytes(ZSend)
            End If

        Catch ex As Exception
            MsgBox("Falsche Eingabe!")
        End Try

        'System.Threading.Thread.Sleep(50)                                                             'Warten 50ms
        SerialPort1.Write(MyArray, 0, 2)

    End Sub
    
    

    Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click     'Disconnect-Button
        SerialPort1.Close()
        Button1.Enabled = True
        Button2.Enabled = False
        Button4.Enabled = False
    End Sub


    Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        If SerialPort1.IsOpen = True Then
            SerialPort1.Close()
        End If
    End Sub

End Class
