0
該代碼用於使用VB.NET運行CMD。我想要做的是,當我輸入「ipconfig」並單擊ExecuteButton時,將出現大量文本,其中一個單詞將是「DNS」。當OutputTextBox中出現「DNS」這個詞時,我希望StatusTextBox顯示文本「It Works」。如何從一個文本框顯示文本到另一個
下面是代碼:
Public Class Form1
Private WithEvents MyProcess As Process
Private Delegate Sub AppendOutputTextDelegate(ByVal text As String)
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.AcceptButton = ExecuteButton
MyProcess = New Process
With MyProcess.StartInfo
.FileName = "CMD.EXE"
.UseShellExecute = False
.CreateNoWindow = True
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
End With
MyProcess.Start()
MyProcess.BeginErrorReadLine()
MyProcess.BeginOutputReadLine()
AppendOutputText("Process Started at: " & MyProcess.StartTime.ToString)
If OutputTextBox.Text = "DNS" Then
StatusTextBox.Text = "It Works"
End If
End Sub
Private Sub Form1_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
MyProcess.StandardInput.WriteLine("EXIT")
MyProcess.StandardInput.Flush()
MyProcess.Close()
End Sub
Private Sub MyProcess_ErrorDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles MyProcess.ErrorDataReceived
AppendOutputText(vbCrLf & "Error: " & e.Data)
End Sub
Private Sub MyProcess_OutputDataReceived(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs) Handles MyProcess.OutputDataReceived
AppendOutputText(vbCrLf & e.Data)
End Sub
Private Sub ExecuteButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ExecuteButton.Click
MyProcess.StandardInput.WriteLine(InputTextBox.Text)
MyProcess.StandardInput.Flush()
InputTextBox.Text = ""
End Sub
Private Sub AppendOutputText(ByVal text As String)
If OutputTextBox.InvokeRequired Then
Dim myDelegate As New AppendOutputTextDelegate(AddressOf AppendOutputText)
Me.Invoke(myDelegate, text)
Else
OutputTextBox.AppendText(text)
End If
End Sub
End Class
這裏是什麼樣子的例子:
要指出我的問題,這裏是我嘗試做:
If OutputTextBox.Text = "DNS" Then
StatusTextBox.Text = "It Works"
End If
當我輸入「ipconfig」時,將顯示文本「DNS」,但不顯示StatusTextBox發生了一件事情。我究竟做錯了什麼?
是的,你說得對,我要檢查它是否包含「DNS」,然後有「這作品」在StatusTextBox顯示。 你的意思是像下面那樣嗎?它不適合我。 私人小組MyProcess_OutputDataReceived(BYVAL發件人爲對象,BYVALË作爲System.Diagnostics.DataReceivedEventArgs)把手MyProcess.OutputDataReceived AppendOutputText(vbCrLf&e.Data) 如果e.Data.Contains( 「DNS」)然後 StatusTextBox.Text =「它工作的」 結束如果 結束小組 – luoxiansheng
通過「它沒有爲我工作」你的意思是你得到一個錯誤約一個跨線程操作?您需要創建一個用於訪問UI的委託,就像您更改輸出文本框一樣。我在上面添加了一些代碼。 – Capellan
對不起,我的短暫沒有工作的答案,我應該早些時候更詳細。但是,你是非常正確的,這是我收到的錯誤。代表確實解決了這個問題。非常感謝! :) – luoxiansheng