要记住的关键是.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的例子),但这应该足以满足你的需要。