我想用线程启动一个CMD进程  CMD是监听程序  不关闭状态的情况下   读取CMD显示的信息 返回到我的textbox上显示现在的情况就是   我可以启动CMD   但是要CMD停止后才能返回结果,还有就是CMD启动之后 不关闭   程序走不下去  不能读取结果。有没有办法一直开启CMD  并且每秒读取CMD的信息显示到textbox上。最好使用2个线程   一个运行CMD,一个负责读取并且显示。
目前我写的部分代码   -----有问题
急    感谢各位高手的指点   给点思路吧。//button事件   负责开启服务
 private void button1_Click(object sender, EventArgs e)
        {           //创建一个线程并且运行CMD进程方法    
            Thread t = new Thread(new ThreadStart(Cmd));
            Thread s = new Thread(new ThreadStart(form));           Thread.Sleep(500);
          
           t.Start();
           s.Start(); 
           
         }
//CMD方法
public  void Cmd()
        {
            //CMD要执行的语句
            string[] cmd = new string[] { "ping 192.168.1.1 -n", "ping 127.0.0.1 -t" };
            //创建CMD进程并且配置
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            //启动进程,并且永不关闭。
            p.Start();
            p.StandardInput.AutoFlush = true;
            for (int i = 0; i < cmd.Length; i++)
            {
                p.StandardInput.WriteLine(cmd[i].ToString());
            }
           
                  
          }
   //读取CMD显示的信息   并且调用显示消息方法、把信息传递给showMessage方法用来显示到textbox。  
 public void form()
        {
                
            string strRst = p.StandardOutput.ReadToEnd();
            this.textBox1.BeginInvoke(new System.EventHandler(showMessage), strRst);
        }//在控件textbox上显示消息的方法
 private void showMessage(object o, System.EventArgs e)
        {                      this.textBox1.Text = o.ToString();        }

解决方案 »

  1.   

    我是要写一个GAME网关   通过CMD开启服务器   并且显示信息到程序上  
    现在CMD可以创建 不知道用什么方法读取CMD显示的信息  
    全部代码就下面这些   还没写完就遇到这问题
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Diagnostics;
    using System.Threading;namespace Ctrl
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }        private void button1_Click(object sender, EventArgs e)
            {
                Thread t = new Thread(new ThreadStart(Cmd));
                Thread s = new Thread(new ThreadStart(form));           Thread.Sleep(500);
              
               t.Start();
               s.Start(); 
               
                       }
            public Boolean Exis(string filename)
            {
                String File_Name = filename.ToString();
                if (File.Exists(File_Name))
                {
                  return true;
                }
                else
                {
                    MessageBox.Show("缺少"+filename+"文件");
                    return false;
                }
            }
            public void Input(string Filename ,string text,string updatetext)
            {
                
                     
                    try
                    {
                        string[] str = File.ReadAllLines(Filename,Encoding.GetEncoding("gb2312"));
                        StreamWriter sw = new StreamWriter(Filename);
                        for (int i = 0; i < str.Length; i++)
                        {
                            if (str[i].IndexOf(text) != -1)
                            {
                                str[i] = text + updatetext;
                            }
                      
                        }
                        for (int i = 0; i < str.Length; i++)
                        {
                            sw.WriteLine(str[i].Trim());
                        }
                        sw.Close();
                    }
                    catch (Exception ce)
                    {
                        MessageBox.Show(ce.ToString());                }
                
           }
            private void Form1_FormClosing_1(object sender, FormClosingEventArgs e)
            {
                if (MessageBox.Show("确定要退出本程序吗?", "询问", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    e.Cancel = false;
                    Process.GetCurrentProcess().Kill();
                }
                else
                {
                    e.Cancel = true;
                }
            }        private void 服务器基本配置ToolStripMenuItem_Click(object sender, EventArgs e)
            {
                ServerInit server = new ServerInit();
                server.Show();        }
            public void form()
            {
                    
                string strRst = p.StandardOutput.ReadToEnd();
                this.textBox1.BeginInvoke(new System.EventHandler(showMessage), strRst);
            }
            Process p = new Process();
            public  void Cmd()
            {
                string[] cmd = new string[] { "start aa.exe", "ping 127.0.0.1 -t" };
                
                p.StartInfo.FileName = "cmd.exe";
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                p.StandardInput.AutoFlush = true;
                for (int i = 0; i < cmd.Length; i++)
                {
                    p.StandardInput.WriteLine(cmd[i].ToString());
                }
               
            }
            private void showMessage(object o, System.EventArgs e)
            {                      this.textBox1.Text = o.ToString();        }
            public static bool CloseProcess(string ProcName)
            {
                bool result = false;
                System.Collections.ArrayList procList = new System.Collections.ArrayList();
                string tempName = "";
                int begpos;
                int endpos;
                foreach (System.Diagnostics.Process thisProc in System.Diagnostics.Process.GetProcesses())
                {
                    tempName = thisProc.ToString();
                    begpos = tempName.IndexOf("(") + 1;
                    endpos = tempName.IndexOf(")");
                    tempName = tempName.Substring(begpos, endpos - begpos);
                    procList.Add(tempName);
                    if (tempName == ProcName)
                    {
                        if (!thisProc.CloseMainWindow())
                            thisProc.Kill(); 
                        result = true;
                    }
                }
                return result;
            }    
        }
    }
      

  2.   

       1. using (Process process = new System.Diagnostics.Process())  
       2. {  
       3.     process.StartInfo.FileName = "ping";  
       4.     process.StartInfo.Arguments = "www.ymind.net";  
       5.     // 必须禁用操作系统外壳程序  
       6.     process.StartInfo.UseShellExecute = false;  
       7.     process.StartInfo.CreateNoWindow = true;  
       8.     process.StartInfo.RedirectStandardOutput = true;  
       9.  
      10.     process.Start();  
      11.  
      12.     string output = process.StandardOutput.ReadToEnd();  
      13.  
      14.     if (String.IsNullOrEmpty(output) == false)  
      15.         this.textBox1.AppendText(output + "\r\n");  
      16.  
      17.     process.WaitForExit();  
      18.     process.Close();  
      19. } 
      

  3.   

    http://topic.csdn.net/u/20091009/16/a56b35d4-245c-4acb-82d1-2737407aaf78.html14 层
      

  4.   

    p.StartInfo.RedirectStandardOutput = true; 
    输出可以自己定位的
      

  5.   

    楼上的方法好像不行   如果把代码放到线程里   是不能调用textBox控件的
    如果是单独运行这个方法    process.StandardOutput.ReadToEnd();读取一次就结束了  
    我想实现的是   CMD一直处于运行状态      并且textBox死循环、每秒readline显示一条CMD信息
      

  6.   

    CMD输出输入重定向
      

  7.   

    Process cmd = new Process();
    cmd.StartInfo.FileName = "";
    cmd.StartInfo.UseShellExecute = false; 
    cmd.StartInfo.RedirectStandardInput = true;
    cmd.StartInfo.RedirectStandardOutput = true; 
    cmd.StartInfo.CreateNoWindow = true;
    cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    cmd.Start(); 
    this.textBox1.Text = cmd.StandardOutput.ReadToEnd();
    cmd.WaitForExit();
    cmd.Close();或
            [DllImport("kernel32.dll")]
            public static extern bool AllocConsole();
            [DllImport("kernel32.dll")]
            public static extern bool FreeConsole();
      static void Main(string[] args)
            {
                try
                {
                    if(args.Length > 0 && args[0].ToLower() == "-c")
                    {
                      System.Environment.GetCommandLineArgs();  
                         AllocConsole();
                    }
                    
                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Application.Run(new Form1());
                }
                finally
                {
                    FreeConsole();
                }
            }
      

  8.   

    楼主给的重定向是我想要的结果   就是没看明白cmd语句要写到哪里 还有显示到textbox的时候  是哪句.
    能给说明一下么   我要执行的是一串CMD语句  最好是用数组  
    还有方法执行顺序   是要线程执行哪个方法    1)初始化 2) 写入数据到管道 是要一起调用 
    还是单独调用一个
      

  9.   

    11楼的高手没了解我的意图   
    创建完CMD运行后是不关闭的   就比方一直在PING 127.0.0.1   走到cmd.start();的时候就成了死循环了     this.textBox1.Text = cmd.StandardOutput.ReadToEnd();这句话是没办法访问到的 
    并且这个方法用线程启动  不能直接调用textbox控件    我的意图是写两个方法   一个负责启动+执行cmd命令    一个负责实时监听cmd显示的结果
      

  10.   

    你把cmd的内容输出到一个txt文件,然后那边去读,不知道可不可以.
      

  11.   

    或者可以简单的点    CMD只负责执行命令 并且死循环。谁告诉我个方法    用来读取我创建的CMD进程显示的结果 并 显示到textbox上 
      

  12.   

    写了个简单的,不知道是不是LZ想要的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 AutoReset = new AutoResetEvent(false);        private void button1_Click(object sender, EventArgs e)
            {
                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;
                cmd.StandardInput.WriteLine("ping 127.0.0.1");            sReader = cmd.StandardOutput;
                
                while (true)
                {
                    Thread getData = new Thread(new ThreadStart(ReadStream));
                    getData.IsBackground = true;
                    getData.Start();
                    if (!AutoReset.WaitOne(10000))
                        break;                textBox1.AppendText(ReadLineString + Environment.NewLine);
                }            MessageBox.Show("End");
            }        private void ReadStream()
            {
                ReadLineString = sReader.ReadLine();
                AutoReset.Set();
            }
        }
    }
      

  13.   


    效果不错   是我想要的结果   
    不过有点小BUG 把ping命令改成127.0.0.1 -t  运行之后程序就死了 
    我想这个小bug我自己能够解决了
    如果我要执行很多条CMD是否重复这句   比如↓
    cmd.StandardInput.WriteLine("start aa.exe"); 
    cmd.StandardInput.WriteLine("start bb.exe"); 
    cmd.StandardInput.WriteLine("ping 127.0.0.1"); 楼主看到后回复一下重复多条cmd命令是否是我上面的方式感谢指点   给分收贴   
      

  14.   

    LZ给分太痛快了,写了个好一点的,支持多个命令的,并且不占用UI线程,不用每次都new Thread,
    改成了用两个AutoResetEvent,可以节省不少资源。
    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();
                }
            }
        }
    }