管道技術一般采用Window API來實現,在C#中實現管道技術其實也很簡單,因為C#中有方便的進程和線程機制。
(1)通過設置Process類,獲取輸出接口,代碼如下:
Process proc = new Process();
proc .StartInfo.FileName = strScript;
proc .StartInfo.WorkingDirectory = strDirectory;
proc .StartInfo.CreateNoWindow = true;
proc .StartInfo.UseShellExecute = false;
proc .StartInfo.RedirectStandardOutput = true;
proc .Start();
(2)設置線程連續讀取輸出的字符串:
eventOutput = new AutoResetEvent(false);
AutoResetEvent[] events = new AutoResetEvent[1];
events[0] = m_eventOutput;
m_threadOutput = new Thread( new ThreadStart( DisplayOutput ) );
m_threadOutput.Start();
WaitHandle.WaitAll( events );
(3)完整線程函數:
private void DisplayOutput()
{
while ( m_procScript != null && !m_procScript.HasExited )
{
string strLine = null;
while ( ( strLine = m_procScript.StandardOutput.ReadLine() ) != null)
{
m_txtOutput.AppendText( strLine + "/r/n" );
m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
m_txtOutput.ScrollToCaret();
}
Thread.Sleep( 100 );
}
m_eventOutput.Set();
}
要注意的是,以下語句使TextBox顯示的總是最新添加的,而AppendText而不使用+=,是因為+=會造成整個TextBox的回顯使得整個顯示區域閃爍
m_txtOutput.AppendText( strLine + "/r/n" );
m_txtOutput.SelectionStart = m_txtOutput.Text.Length;
m_txtOutput.ScrollToCaret();
為了不阻塞主線程,可以將整個過程放到一個另一個線程里。
新聞熱點
疑難解答
圖片精選