管道技术一般采用Window API来实现,最近试着用C#来实现Windows管道技术,发现C#本身方便的进程线程机制使工作变得简单至极,随手记录一下,推荐给大家。

  首先,我们可以通过设置Process类,获取输出接口,代码如下:
 

1C#实现Window管道技术  Process proc = new Process(); 
2C#实现Window管道技术  proc .StartInfo.FileName = strScript; 
3C#实现Window管道技术  proc .StartInfo.WorkingDirectory = strDirectory; 
4C#实现Window管道技术  proc .StartInfo.CreateNoWindow = true
5C#实现Window管道技术  proc .StartInfo.UseShellExecute = false
6C#实现Window管道技术  proc .StartInfo.RedirectStandardOutput = true
7C#实现Window管道技术  proc .Start();

 

  然后设置线程连续读取输出的字符串:
 

1C#实现Window管道技术  eventOutput = new AutoResetEvent(false); 
2C#实现Window管道技术  AutoResetEvent[] events = new AutoResetEvent[1]; 
3C#实现Window管道技术  events[0= m_eventOutput; 
4C#实现Window管道技术
5C#实现Window管道技术  m_threadOutput = new Thread( new ThreadStart( DisplayOutput ) ); 
6C#实现Window管道技术  m_threadOutput.Start(); 
7C#实现Window管道技术  WaitHandle.WaitAll( events );


  线程函数如下:
 

 1C#实现Window管道技术  private void DisplayOutput() 
 2  }

  这里要注意的是,使用以下语句使TextBox显示的总是最新添加的,而AppendText而不使用+=,是因为+=会造成整个TextBox的回显使得整个显示区域闪烁 
 

1C#实现Window管道技术  m_txtOutput.AppendText( strLine + "\r\n" ); 
2C#实现Window管道技术  m_txtOutput.SelectionStart = m_txtOutput.Text.Length; 
3C#实现Window管道技术  m_txtOutput.ScrollToCaret();
4C#实现Window管道技术

相关文章:

  • 2022-03-06
  • 2021-08-05
  • 2021-08-27
  • 2021-10-07
  • 2022-12-23
  • 2021-09-17
  • 2021-07-07
猜你喜欢
  • 2021-09-28
  • 2021-10-03
  • 2021-09-22
  • 2022-01-29
  • 2022-12-23
  • 2021-12-04
相关资源
相似解决方案