using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows.Forms;

namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private string ReadLineString;
private StreamReader sReader;
AutoResetEvent MainReset
= new AutoResetEvent(false);
AutoResetEvent ThreadReset
= new AutoResetEvent(false);

private void button1_Click(object sender, EventArgs e)
{
string[] CommandArray = new string[]{ping 127.0.0.1, ping 192.168.0.1};
ParameterizedThreadStart pThreadStart
= new ParameterizedThreadStart(StartCommand);
Thread Run
= new Thread(pThreadStart);
Run.IsBackground
= true;
Run.Start(CommandArray);
}

private void StartCommand(object cmds)
{
Process cmd
= new Process();
cmd.StartInfo.UseShellExecute
= false;
cmd.StartInfo.RedirectStandardInput
= true;
cmd.StartInfo.RedirectStandardOutput
= true;
cmd.StartInfo.CreateNoWindow
= true;
cmd.StartInfo.WindowStyle
= ProcessWindowStyle.Hidden;
cmd.StartInfo.FileName
= cmd.exe;
cmd.Start();
cmd.StandardInput.AutoFlush
= true;
sReader
= cmd.StandardOutput;

string[] commands = cmds as string[];

foreach (string commandLine in commands)
{
cmd.StandardInput.WriteLine(commandLine);
Thread getData
= new Thread(new ThreadStart(ReadStream));
getData.IsBackground
= true;
getData.Start();

while (true)
{
//设置命令超时
if (!MainReset.WaitOne(2000))
{
getData.Abort();
break;
}

textBox1.Invoke(new InvokeDelegate(InvokeMethod)); ;
ThreadReset.Set();
}
}
}

private delegate void InvokeDelegate();

public void InvokeMethod()
{
textBox1.AppendText(ReadLineString
+ Environment.NewLine);
}

private void ReadStream()
{
while (true)
{
ReadLineString
= sReader.ReadLine();
MainReset.Set();
ThreadReset.WaitOne();
}
}
}
}


历史博文

标签:,
十一月 6, 2009 at 10:39 下午 by yippee 3 次
Category: Info
Tags: ,