覚えておくべき重要な点は、.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 を参照してください) が、必要なことを行うにはこれで十分です。