2015-11-20 57 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

它的作品像魅力。我試過你的代碼的第一部分,它的工作原理。謝謝你,馬特。 (對於第二部分,我還沒有研究^^)。 –