每次迭代时字符串中的可视基本显示字符

时间:2013-09-21 19:18:00

标签: vb.net

我有一个包含以下内容的文本文件:

  

12 13 32 41; 321 433 412 234; ...

我正在尝试读取数字并在添加它们之前在标签上显示它们。我在“;”之前添加了每组数字。输出应该是:

  

12 + 13 + 32 + 41 = 98。

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim L As Integer
    Dim i As Integer
    Dim c As Char
    Dim res As String
    Dim file As String

    OpenFileDialog1.ShowDialog()
    path = OpenFileDialog1.FileName
    File = My.Computer.FileSystem.ReadAllText(path)
    L = File.Length
    For i = 1 To L Step 1
        c = Mid(Options.File, i)
        If c <> " " Then
            res = res & c
        Else
            Label1.Text = res
                 ' messagebox.show(res)   
            System.Threading.Thread.Sleep(100)

            res = ""
        End If
    Next
End Sub

我的问题是只显示文件的最后一个数字。我没有发布添加部分。

请帮助我是visual basic

的新手

2 个答案:

答案 0 :(得分:1)

如果您希望更新缓慢发生,您可以依赖窗口的正常消息队列来更新显示。您可以使用计时器更改显示的内容。使用Thread.Sleep()是一个坏主意,因为它使UI无响应。此代码允许同时更新多个Control:

Class TextRevealer
Property target As Control
Property text As String

Private nChars As Integer
Private tim As Timer

Sub New(target As Control, text As String)
    Me.target = target
    Me.text = text
    nChars = 1
    tim = New Timer
    tim.Interval = 100
    AddHandler tim.Tick, AddressOf RevealText
End Sub

Sub Start()
    If tim IsNot Nothing Then
        tim.Start()
    End If
End Sub
Private Sub RevealText(sender As Object, e As EventArgs)
    target.Text = text.Substring(0, nChars)
    nChars += 1
    If nChars = text.Length Then
        tim.Stop()
        tim.Dispose()
    End If
End Sub
End Class

 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Clic
    Dim txt = IO.File.ReadAllText("C:\temp\crop.txt")
    Dim txtRvlr = New TextRevealer(Label1, txt)
    txtRvlr.Start()

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Dim txt = IO.File.ReadAllText("C:\temp\dives.txt")
    Dim txtRvlr = New TextRevealer(Label2, txt)
    txtRvlr.Start()

End Sub

答案 1 :(得分:0)

Thread.Sleep(100)错误1秒延迟。睡眠是以毫秒为单位,因此您需要1000秒1秒。

另一个问题是当你让你的线程进入睡眠状态时,你的表单不会重新绘制。尝试

Label1.Text = res
Label1.Refresh  
' or maybe Label1.Update
Threading.Thread.Sleep(1000)

RefreshUpdate都告诉控件重绘自己,但这实际上只是在队列中放置了一条绘制消息,它仍然可能在你让线程进入睡眠状态之前不会处理msg。 / p>

另一种方法是使用Timer来测量1秒的时间。