【问题标题】:Type String Out In TextBox (VB.NET)在文本框中键入字符串输出 (VB.NET)
【发布时间】:2014-06-26 20:10:37
【问题描述】:

我试图让我的应用程序看起来好像正在将字符串输入到文本框中。我的代码的主要问题似乎是 thread.sleep 不会为每个单独的字符而睡眠,而只是整个应用程序。例如,如果我用字符串“hello”调用sub,它将停止100毫秒,然后TextBox将立即显示“hello”。

Sub typeOut(ByVal toType As String)
    toType = toType.ToCharArray()
    For Each letter As Char In toType
        TextBox2.Text = TextBox2.Text + letter
        Threading.Thread.Sleep(100)
    Next
End Sub

感谢您的帮助!

【问题讨论】:

  • 您正在让 UI 线程休眠,然后才能显示新字符。
  • @Plutonix 我该如何解决这个问题?
  • 在循环中尝试TextBox2.Refresh
  • @Plutonix 谢谢,在我看到这个之前就想通了!
  • 更好的方法是完全不在 UI 线程上Sleep()。如果你可以使方法Async,它会更干净Await Task.Delay(100)

标签: vb.net string


【解决方案1】:

这是计时器的理想工作。您甚至可以做到这一点,这样您就可以同时以不同的速度输入多个 TextBox。

概念演示:我在一个新的 Windows Forms 项目窗体上放置了两个 TextBox 和两个 Button,并使用以下代码来实现:

Public Class Form1

    Private Class TypeText
        Property Target As TextBox
        Property TextToType As String

        Private tim As System.Windows.Forms.Timer
        Private currentChar As Integer

        Private Sub EmitCharacters(sender As Object, e As EventArgs)
            Target.Text &= TextToType.Chars(currentChar)
            currentChar += 1
            If currentChar = TextToType.Length Then
                RemoveHandler tim.Tick, AddressOf EmitCharacters
                tim.Dipose()
            End If
        End Sub

        Public Sub Start()
            AddHandler tim.Tick, AddressOf EmitCharacters
            tim.Start()
        End Sub

        'TODO: add Stop, Pause, Restart etc. methods if needed

        Public Sub New(target As TextBox, textToType As String, interval As Integer)
            Me.Target = target
            Me.TextToType = textToType
            tim = New System.Windows.Forms.Timer
            tim.Interval = interval
            currentChar = 0
        End Sub

    End Class

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Dim typer As New TypeText(TextBox1, "Hello, World!", 200)
        typer.Start()
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
        Dim typer As New TypeText(TextBox2, "This is some other text.", 350)
        typer.Start()
    End Sub

End Class

【讨论】:

    猜你喜欢
    • 2014-08-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多