0

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

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 的新手

4

2 回答 2

1

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

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
于 2013-09-21T20:37:14.343 回答
0

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

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

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

两者都Refresh告诉Update控件重新绘制自己,但这实际上只是将绘制消息放入队列中,在您使线程进入睡眠状态之前它可能仍然不会处理消息。

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

于 2013-09-21T20:19:45.687 回答