我正在尝试使我的应用程序看起来好像在文本框中输入了一个字符串。我的代码的主要问题似乎是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
感谢您的帮助!
答案 0 :(得分:0)
这是Timer的理想工作。您甚至可以制作它,以便可以以不同的速度同时输入多个TextBox。
概念演示:我在新的Windows窗体项目表单上放置了两个TextBox和两个Buttons,并使用以下代码来实现:
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