如何将文本连续输出到RichTextBox,它在视觉上是显而易见的?

问题描述 投票:1回答:1

我现在正在尝试创建自己的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并不断地一次又一次地在一个新行上输出一个字符串。

vb.net winforms for-loop while-loop richtextbox
1个回答
0
投票

如上所述:

  • 创建一个System.Windows.Forms.Timer。有不同类型的计时器可用。这是更新UI组件所需的,因为它在UI线程中引发了Tick事件。
  • 初始化Timer并将其Interval设置为1秒(1000 ms)。初始化在表单的Shown()事件中执行,当表单准备好呈现时会引发该事件(请参阅文档)。
  • 添加Timer.Tick事件处理程序(这里添加了代码)
  • 初始化一个Integer字段(此处称为timerCounter),每次定时器Tick时都会递增。
  • 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
© www.soinside.com 2019 - 2024. All rights reserved.