![](/img/trans.png)
[英]How to append text to the richTextBox from another class in C# Winform?
[英]How to append text to the richTextBox from another class in VB.NET Winform?
我有一個名為Form1.vb的winform和一個名為FZConsole.vb的類。在winform上,我有一個Richtextbox1,我試圖將文本附加到該類中,但它不起作用。
從Form1.vb,我可以輕松地執行
Richtextbox1.AppendText("Console is currently ON.")
在課堂上,我嘗試執行此操作,但是它不起作用:
Class FZConsole
Public Sub FZConsole()
While True
Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class")
Threading.Thread.Sleep(1)
End While
End Sub
End Class
從另一個線程訪問控件時,通常必須調用控件的訪問/更新。 這樣做是為了同步控件的更新,以使兩個線程不會同時更新一個控件。
您可以這樣想:兩個人不能同時寫同一篇論文。
調用通常並不難。 基本上,這只是做這兩件事:
調用是使用Delegate方法執行的。 如果目標是.NET Framework 4.0或更高版本,則可以使用Sub()
lambda表達式來創建一個非常簡單的委托。
Public Sub FZConsole()
While True
If Form1.InvokeRequired = True Then 'Invocation is required.'
Form1.Invoke(Sub() Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class"))
Else 'Invocation is not required.'
Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class")
End If
Threading.Thread.Sleep(1)
End While
End Sub
但是,如果您以.NET Framework 3.5或更低版本為目標,則有些麻煩。 以較早的框架為目標時,您必須自己聲明委托,這並不像使用lambda那樣簡單,因為在傳遞變量時,lambda的工作方式有所不同。
Delegate Sub TextUpdaterDelegate(ByVal Text As String)
Public Sub FZConsole()
While True
If Form1.InvokeRequired = True Then 'Invocation is required.'
Form1.Invoke(New TextUpdaterDelegate(AddressOf RichTextBox1.AppendText), Environment.NewLine & "Test From Class")
Else 'Invocation is not required.'
Form1.Richtextbox1.AppendText(Environment.NewLine & "Test From Class")
End If
Threading.Thread.Sleep(1)
End While
End Sub
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim newInstanceToClass As New SomeClass
RichTextBox1.AppendText(newInstanceToClass.returenText)
End Sub
Class SomeClass
Function returenText() As String
Dim txt As String = "some text..."
Return txt
End Function
End Class
End Class
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.