如何连续输出文本到RichTextBox并在视觉上引人注意?

时间:2019-04-11 21:42:39

标签: vb.net winforms for-loop while-loop richtextbox

我现在正在尝试创建自己的VB项目以熟悉该语言,而我要做的就是不断地在RichTextBox的下一行中打印一个字符串。
我不知道的问题是让它一个接一个地打印,它是一次打印所有。下面有一些代码可以显示我现在的位置。

我尝试使用不同的计数方法,并且根据其设置方式,调试器甚至不会加载...

Friend WithEvents TableLayoutPanel1 As System.Windows.Forms.TableLayoutPanel
Friend WithEvents Button1 As System.Windows.Forms.Button

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
End Sub
Private Sub RTB1_TextChanged(sender As System.Object, e As System.EventArgs)
End Sub

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim counter1 As Integer = 0
    Dim i As String = "- I" & vbCrLf

    While counter1 <= 10
        Timer1.Interval = 1000
        Timer1.Start()
        i = i + i
        counter1 += 1
    End While

    RichTextBox1.Text = i


    'Loop

    'Environment.NewLine

End Sub
Friend WithEvents TableLayoutPanel2 As System.Windows.Forms.TableLayoutPanel

Private Sub TableLayoutPanel2_Paint(sender As System.Object, e As System.Windows.Forms.PaintEventArgs) Handles TableLayoutPanel2.Paint

End Sub
Friend WithEvents RichTextBox1 As System.Windows.Forms.RichTextBox

Private Sub RichTextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles RichTextBox1.TextChanged
    RichTextBox1.SelectionStart = RichTextBox1.Text.Length
    RichTextBox1.ScrollToCaret()
End Sub
Friend WithEvents Timer1 As System.Windows.Forms.Timer

感谢您抽出宝贵时间来研究这个问题,并帮助我!
我真的在寻找我的输出来向下滚动RichTextBox,并不断在新行中一次又一次地输出一个字符串。

1 个答案:

答案 0 :(得分:0)

如上所述:

  • 创建一个System.Windows.Forms.Timer。有不同类型的计时器。这是您需要更新UI组件的组件,因为它在UI线程中引发了Tick事件。
  • 初始化计时器并将其间隔设置为1秒(1000 ms)。初始化在表单的Shown()事件中执行,在准备好呈现表单时会引发该事件(请参阅文档)。
  • 添加Timer.Tick事件处理程序(此处已在代码中添加)
  • 初始化一个Integer字段(在此称为 timerCounter ),该字段在每次Timer Ticks时递增。
  • Tick事件中,使用其AppendText()方法向RichTextBox控件添加一行文本,该方法允许在不清除文本的情况下向该控件添加文本。此方法对于继承TextBoxBase的所有控件都是通用的。

注意:
我正在使用插值字符串$"{Some value}"将文本添加到RichTextBox中。如果您的VB.Net版本不支持它,请使用旧格式:

RichTextBox1.AppendText("Line number " & timerCounter.ToString() & Environment.NewLine)


Private rtbTimer As System.Windows.Forms.Timer
Private timerCounter As Integer = 0

Protected Sub TimerTick(sender As Object, e As EventArgs)
    timerCounter += 1
    RichTextBox1.AppendText($"Line number {timerCounter} {Environment.NewLine}")
    RichTextBox1.ScrollToCaret()
End Sub

Private Sub Form1_Shown(sender As Object, e As EventArgs) Handles MyBase.Shown
    rtbTimer = New Windows.Forms.Timer With { .Interval = 1000 }
    AddHandler rtbTimer.Tick, AddressOf TimerTick
    rtbTimer.Start()
End Sub