2015-11-20 49 views
0

我是VB noobie并使用定时器编码一个小练习。使用定时器发送文本行到记事本

经过多次尝试,我无法让它工作。我需要将RichTextBox的每一行(txtcontent)发送给打开的记事本。

我将计时器间隔设置为1000ms(1s),对文本框行进行计数并发送(首先尝试使用messagebox)。但是,每次msgbox只显示一行并继续重复。请纠正我。 〜下面是我的计时器代码:

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 
+0

什么是txtContent?一个TextBox元素?你究竟想要做什么?每次计时器滴答应该发送所有的文本文本到记事本? –

+1

不知道为什么这是downvoted,因为它似乎是一个非常有效的问题给我 –

回答

2

我想你遇到的问题是计时器不断有射击你点击了你的消息框前,即是重入问题的事实。

如果您在进入子程序,并在年底启用它,你会看到,它确实循环线禁止定时器:

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 

发送每一行到记事本是一个比较参与其中。虽然记事本理论并支持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 
+0

它的作品像魅力。我试过你的代码的第一部分,它的工作原理。谢谢你,马特。 (对于第二部分,我还没有研究^^)。 –