在不同的线程和代码文件中向richTextBox添加文本



为了创建一个与串行端口设备接口的程序,我最近开始学习vb.net。为了保持结构整洁,vb代码被分成了两个地方;第一个是用于初始化,点击按钮等的代码,而第二个是用于管理通信端口。分别命名为'MainWindow.xaml.vb'和'ComPortManager.vb'。

在"comPortManager.vb":

Dim RXArray(2047) As Char ' Array to hold received characters
Dim RXCnt As Integer      ' Received character count
    Private Sub comPort_DataReceived(ByVal sender As Object, ByVal e As SerialDataReceivedEventArgs) Handles comPort.DataReceived
        Do
            RXCnt = 0
            Do
                 'Populates the array, RXArray and counts the number of characters, RXCnt
            Loop Until (comPort.BytesToRead = 0) 'Keeps reading the buffer until it is empty
            'Code for posting to the richTextBox
        Loop Until (comPort.BytesToRead = 0) 'If the buffer has been written to in the meantime, repeat
    End Sub

"主窗口。xaml'包含一个功能区(微软2010年10月发布),控制设置,打开,关闭和发送(现在保持所有的分离和简单),与窗口的其余部分是一个名为'RichTextBox1'的richTextBox。

搜索一种方法来张贴RXArray的内容RichTextBox1提出了许多建议,基于调用或BeginInvoke。实际上,工作示例已经成功运行,但是与Invoke相关的所有代码都在一个文件中,即后面的代码。(如果我错了请纠正我,但这听起来对小程序很好,但对于中型到大型程序可能会变得臃肿,因此我想找到一个更好的解决方案)

最接近运行的代码(我相信)如下:

"comPort_DataReceived……在填充数组

之后
If RichTextBox1.InvokeRequired Then
                RichTextBox1.Invoke(New MethodInvoker(AddressOf Display))
            End If

'并返回到主代码

Public Delegate Sub MethodInvoker()
Private Sub Display()
    RichTextBox1.AppendText(New String(RXArray, 0, RXCnt))
End Sub

这有一些问题,我不确定在这个阶段要往哪个方向走。RichTextBox1是在一个不同的线程,因此不被识别;invokerrequirequired不是System.Windows.Controls的成员。RichTextBox,同样与调用;最后,在示例中,名为MethodInvoker的委托从未如上所述。

任何关于这个话题的帮助都是非常感谢的。在这几个星期里,Invoke, BeginInvoke等有点让我无法理解。问候,乔纳森。

我们有一个大规模的应用程序,其中一个文本框有多个线程的状态,并发地附加到它上面,并且来自不同的形式。这是它的简化版本:

Public Sub addToMessageBox(ByVal msg As String)
    If Me.InvokeRequired Then
      Dim d As New AddToMessageBoxDelegate(AddressOf Me.addToMessageBox)
      Me.BeginInvoke(d, New Object() {msg})
    Else
      Try
        Me.MessageBox.AppendText("--" + msg + vbCrLf)
      Catch ex As Exception
      End Try
    End If
  End Sub

委托在开头声明

Private Delegate Sub AddToMessageBoxDelegate(ByVal msg As String)

我能看到的最大区别是我使用了父类的beginInvoke()和invokerrequiredd()。我建议你试一试。调用parentClass。

AddToMessageBox("你想要追加的文本")在你调用display()的地方

最新更新