Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class Form1
Dim myPort As Array
Delegate Sub SetTextCallback(ByVal [int] As String)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
postComboBox1.Items.AddRange(myPort)
End Sub
Private Sub addbutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles addbutton.Click
SerialPort1.PortName = postComboBox1.Text
SerialPort1.BaudRate = baudComboBox2.Text
SerialPort1.Open()
addbutton.Enabled = False
closebutton.Enabled = True
End Sub
Private Sub closebutton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closebutton.Click
SerialPort1.Close()
addbutton.Enabled = True
closebutton.Enabled = False
End Sub
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
Private Sub ReceivedText(ByVal [text] As String)
If Me.inputTextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.inputTextBox2.Text &= [text]
End If
End Sub
End Class
Private Sub ReceivedText(ByVal [text] As String)
If Me.inputTextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
If [text] > "" Then
Me.inputTextBox2.Text &= [text]
Else
SerialPort1.Close()
End If
End If
End Sub
และ ใน sub นี้ Code (VB.NET)
Private Sub SerialPort1_DataReceived( ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
If Not SerialPort1.IsOpen Then
'Do other method
End If
End Sub
Dim chkEof As Boolean 'ถ้าประกาศตัวแปรผิด ก็แก้ไขหน่อยครับ ไม่ได้ใช้นานแล้ว
Private Sub ReceivedText(ByVal [text] As String)
If Me.inputTextBox2.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
If [text] > "" Then
Me.inputTextBox2.Text &= [text]
chkEof = false
Else
chkEof= true; 'SerialPort1.Close()
End If
End If
End Sub
Private Sub SerialPort1_DataReceived( ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
If chkEof Then
'Do other method
chkEof = false;
End If
End Sub