我是VB新手,正在使用计时器编写一个小练习。
经过多次尝试,我还是没能成功。我需要将RichTextBox(txtcontent
)的每一行都发送到打开的记事本。
我将计时器间隔设置为1000ms(1s),计算文本框的行数,然后发送(首先我尝试使用messagebox)。然而,每次消息框只显示第一行并不断重复。请纠正我。~下面是我的计时器代码:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Static j As Integer = 0
Dim lineCount As Integer = txtcontent.Lines.Length
If j <= lineCount - 1 Then
MsgBox(txtcontent.Lines(j)) 'textbox line
End If
j += 1
End Sub
我认为您遇到的问题是,在您点击消息框之前,计时器一直在启动,即存在重新进入问题。
如果你在进入子程序时禁用计时器,并在最后启用它,你会看到它确实在线路中循环:
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Enabled = False
Static j As Integer = 0
Dim lineCount As Integer = txtContent.Lines.Length
If j <= lineCount - 1 Then
MsgBox(txtContent.Lines(j)) 'textbox line
End If
j += 1
Timer1.Enabled = True
End Sub
将每一行都发送到记事本需要更多的时间。虽然Notepad在理论上确实支持StandardInput,但它的工作存在问题,因此可以使用SendKeys:
Private _notePadProcess As Process = Nothing
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Timer1.Enabled = False
Static j As Integer = 0
Dim lineCount As Integer = txtContent.Lines.Length
If j <= lineCount - 1 Then
WriteLineToNotePad(txtContent.Lines(j))
End If
j += 1
Timer1.Enabled = True
End Sub
<DllImport("user32.dll")>
Private Shared Function SetForegroundWindow(hWnd As IntPtr) As Boolean
End Function
Private Sub WriteLineToNotePad(line As String)
If _notePadProcess Is Nothing OrElse _notePadProcess.HasExited OrElse _notePadProcess.MainWindowHandle = IntPtr.Zero Then
Dim startInfo As New ProcessStartInfo("notepad.exe")
_notePadProcess = Process.Start(startInfo)
Do Until _notePadProcess.MainWindowHandle <> IntPtr.Zero
'wait
Loop
End If
SetForegroundWindow(_notePadProcess.MainWindowHandle)
SendKeys.Send(line + vbCr)
End Sub