如何将收到的序列文本放入多个文本框?

时间:2016-06-29 14:00:42

标签: vb.net serial-port serial-communication rs485

我正在进行一个串行通信项目,并希望收到的字符串进入一个文本框,根据单击哪个按钮发送初始字符串并调用响应。

ReceivedText的代码是:

PrivateSub ReceivedText(ByVal [text] As String)

   Button1.Clear()
   Button2.Clear()

   If Button1.InvokeRequired Then
       RichTextBox1.text = [text].Trim("!")
   End If

   If Button2.InvokeRequired Then
       RichTextBox2.Text = [text].Trim("!")
   End If

EndSub

这只会导致收到的字符串进入两个的框而不是一个或另一个。

有没有办法让文字进入相应的框?

1 个答案:

答案 0 :(得分:0)

要记住的关键是.Net将所有串行通信视为线程。让我举一个简单的例子来更新我从我的一个程序中读取文本框的文本框。

Private Sub ComScale_DataReceived(sender As System.Object, e As System.IO.Ports.SerialDataReceivedEventArgs) Handles ComScale.DataReceived

    If ComScale.IsOpen Then
        Try
            ' read entire string until .Newline 
            readScaleBuffer = ComScale.ReadLine()

            'data to UI thread because you can't update the GUI here
            Me.BeginInvoke(New EventHandler(AddressOf DoScaleUpdate))

        Catch ex As Exception : err(ex.ToString)

        End Try
    End If
End Sub

您将注意到调用例程DoScaleUpdate来执行GUI操作:

Public Sub DoScaleUpdate(ByVal sender As Object, ByVal e As System.EventArgs)
    Try
        'getAveryWgt just parses what was read into something like this {"20.90", "LB", "GROSS"}
        Dim rst() As String = getAveryWgt(readScaleBuffer)
        txtWgt.Text = rst(0)
        txtUom.Text = rst(1)
        txttype.Text = rst(2)
    Catch ex As Exception : err(ex.ToString)

    End Try
End Sub

如果你选择的话,你可以让它变得更加复杂(参见this thread的第15页的例子),但这应该足以满足你的需要。