0

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

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

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

有没有办法让文本进入适当的框中?

4

1 回答 1

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

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

于 2016-07-12T15:22:02.623 回答