我的VB应用程序应使用StreamReader读取文本并在标签中显示.txt文件内容:
Private Sub FileLocationButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles FileLocationButton.Click
OpenFileDialog1.ShowDialog()
End Sub
Private Sub OpenFileDialog1_FileOk(ByVal sender As System.Object, ByVal e As System.ComponentModel.CancelEventArgs) Handles OpenFileDialog1.FileOk
If OpenFileDialog1.FileName <> "" Then
Dim SR As New StreamReader(OpenFileDialog1.FileName)
Do Until SR.EndOfStream
Label6.Text = Label6.Text & SR.ReadLine & vbCrLf
Loop
SR.Close()
End If
End Sub
我正在编写并将文本文件保存在MS Word等中,并希望在vb app中查看文件的更新版本(文本)。
因此:
我添加了一个计时器,想知道什么代码允许应用程序每隔3秒用它的新文本(来自.txt文件)刷新标签,以便我在MS Word中输入的新内容/记事本等会显示?
答案 0 :(得分:0)
您可以使用计时器刷新标签中的文本。在表单设计器中,将Timer从工具箱拖到主窗体(Form1)上。将FilePath属性添加到首选项窗体(Preferences1)并使用它来存储在OpenFileDialog中选择的路径。当您显示首选项表单时,将其路径保存在主窗体中的类级别变量中,并以3000的间隔启动计时器(这是毫秒,因此3000是3秒)。在计时器Tick事件中,再次读取文件并替换标签中的文本。请注意,以下代码使用File.ReadAllText在一个语句中读取文件(并将其关闭)。
在主窗体(Form1)中,您有此代码
Private textFile As String
Sub PrefButton_Click(sender As Object, e As EventArgs) Handles PrefButton.Click
Using pref As New Preferences1
pref.ShowDialog
textFile = pref.FilePath
End Using
If textFile <> "" Then Label6.Text = File.ReadAllText(textFile)
Timer1.Interval = 3000
Timer1.Start
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) _
Handles Timer1.Tick
If textFile <> "" Then Label6.Text = File.ReadAllText(textFile)
End Sub
在首选项表单(Preferences1)中,您有此代码
Private myPath As String
Public ReadOnly Property FilePath As String
Get
Return myPath
End Get
End Property
Private Sub FileLocationButton_Click(sender As Object, e As EventArgs) _
Handles FileLocationButton.Click
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
myPath = OpenFileDialog1.FileName
End If
End Sub