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 がすべてのシリアル通信をスレッドとして扱うことです。スケールからデータを読み取る私のプログラムの 1 つからテキスト ボックスを更新する簡単な例を挙げましょう。

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

GUI 処理を行うルーチン DoScaleUpdate が呼び出されることに注意してください。

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 に答える