码迷,mamicode.com
首页 > 其他好文 > 详细

客户端调用 CMD 命令并回显结果。

时间:2014-06-23 00:51:01      阅读:334      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   code   tar   ext   

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Diagnostics;

namespace Ping
{
    // 1.定义委托  
    public delegate void DelegateReadResultOutput(string result);

    public partial class Form1 : Form
    {
        // 2.定义委托事件  
        public event DelegateReadResultOutput ReadResultOutput1;

        private readonly string basePath = "";

        public Form1()
        {
            InitializeComponent();
            Init();

            basePath = AppDomain.CurrentDomain.BaseDirectory;
        }

        private void Init()
        {
            //3.将相应函数注册到委托事件中  
            ReadResultOutput1 += ReadResultOutputAction1;
        }

        private int i1;

        private string dir1;

        private void FileCheck(string path)
        {
            if (!File.Exists(path))
            {
                File.Create(path).Close();
            }
        }

        public string File1
        {
            get
            {
                return dir1 + DateTime.Now.ToString("yyyy-MM-dd") + ".log";
            }
        }

        private Process CmdProcess1;

        private void button1_Click(object sender, EventArgs e)
        {
            dir1 = basePath + textBox1.Text + "\\";
            if (!Directory.Exists(dir1))
            {
                Directory.CreateDirectory(dir1);
            }

            FileCheck(File1);

            button1.Enabled = false;

            CmdProcess1 = new Process
            {
                StartInfo =
                {
                    FileName = "ping.exe",
                    Arguments = textBox1.Text + " -t",
                    CreateNoWindow = true,
                    UseShellExecute = false,
                    RedirectStandardInput = true,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true
                }
            };
            CmdProcess1.OutputDataReceived += CmdProcess1_OutputDataReceived;
            CmdProcess1.EnableRaisingEvents = true;                      // 启用Exited事件  
            CmdProcess1.Exited += CmdProcess1_Exited;
            CmdProcess1.Start();
            CmdProcess1.BeginOutputReadLine();
            CmdProcess1.BeginErrorReadLine();
        }

        private readonly Queue<string> queueResult1 = new Queue<string>(10);
        private readonly Queue<string> queueResult2 = new Queue<string>(10);

        void CmdProcess1_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                Invoke(ReadResultOutput1, new object[] { e.Data });
            }
        }

        private void ReadResultOutputAction1(string result)
        {
            richTextBox1.Clear();
            if (queueResult1.Count > 8)
            {
                queueResult1.Dequeue();
            }
            result = result + "  " + DateTime.Now;
            queueResult1.Enqueue(result);
            foreach (string r in queueResult1)
            {
                richTextBox1.AppendText(r + Environment.NewLine);
            }

            i1++;
            if (i1 % 5 == 1)
            {
                FileCheck(File1);
                using (TextWriter safewriter1 = TextWriter.Synchronized(new StreamWriter(File1, true)))
                {
                    safewriter1.WriteLine(result);
                }
            }
        }

        private void CmdProcess1_Exited(object sender, EventArgs e)
        {
            FileCheck(File1);
            using (TextWriter safewriter1 = TextWriter.Synchronized(new StreamWriter(File1, true)))
            {
                safewriter1.WriteLine("ping 终止。");
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            FileCheck(File1);
            using (TextWriter safewriter1 = TextWriter.Synchronized(new StreamWriter(File1, true)))
            {
                safewriter1.WriteLine("ping 终止。");
            }
            if (CmdProcess1 != null)
            {
                CmdProcess1.Kill();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;

namespace CmdCallbackShow
{
    // 1.定义委托
    public delegate void DelReadStdOutput(string result);
    public delegate void DelReadErrOutput(string result);

    public partial class Form1 : Form
    {
        // 2.定义委托事件
        public event DelReadStdOutput ReadStdOutput;
        public event DelReadErrOutput ReadErrOutput;

        public Form1()
        {
            InitializeComponent();
            Init();
        }

        private void Init()
        {
            //3.将相应函数注册到委托事件中
            ReadStdOutput += new DelReadStdOutput(ReadStdOutputAction);
            ReadErrOutput += new DelReadErrOutput(ReadErrOutputAction);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 启动进程执行相应命令,此例中以执行ping.exe为例
            RealAction("ping.exe", textBox1.Text);
        }
        
        private void RealAction(string StartFileName, string StartFileArg)
        {
            Process CmdProcess = new Process();
            CmdProcess.StartInfo.FileName = StartFileName;      // 命令
            CmdProcess.StartInfo.Arguments = StartFileArg;      // 参数

            CmdProcess.StartInfo.CreateNoWindow = true;         // 不创建新窗口
            CmdProcess.StartInfo.UseShellExecute = false;
            CmdProcess.StartInfo.RedirectStandardInput = true;  // 重定向输入
            CmdProcess.StartInfo.RedirectStandardOutput = true; // 重定向标准输出
            CmdProcess.StartInfo.RedirectStandardError = true;  // 重定向错误输出
            //CmdProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

            CmdProcess.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);
            CmdProcess.ErrorDataReceived += new DataReceivedEventHandler(p_ErrorDataReceived);

            CmdProcess.EnableRaisingEvents = true;                      // 启用Exited事件
            CmdProcess.Exited += new EventHandler(CmdProcess_Exited);   // 注册进程结束事件

            CmdProcess.Start();
            CmdProcess.BeginOutputReadLine();
            CmdProcess.BeginErrorReadLine();

            // 如果打开注释,则以同步方式执行命令,此例子中用Exited事件异步执行。
            // CmdProcess.WaitForExit();     
        }

        private void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                // 4. 异步调用,需要invoke
                this.Invoke(ReadStdOutput, new object[] { e.Data });
            }
        }

        private void p_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (e.Data != null)
            {
                this.Invoke(ReadErrOutput, new object[] { e.Data });
            }
        }

        private void ReadStdOutputAction(string result)
        {
            this.textBoxShowStdRet.AppendText(result + "\r\n");
        }

        private void ReadErrOutputAction(string result)
        {
            this.textBoxShowErrRet.AppendText(result + "\r\n");
        }

        private void CmdProcess_Exited(object sender, EventArgs e)
        {
            // 执行结束后触发
        }
    }
}

 

string ProcessName="explorer";//这里换成你需要删除的进程名称
Process[] MyProcess1=Process.GetProcessesByName(ProcessName);
Process MyProcess=new Process();//设定程序名
MyProcess.StartInfo.FileName="cmd.exe";//关闭Shell的使用
MyProcess.StartInfo.UseShellExecute=false;//重定向标准输入
MyProcess.StartInfo.RedirectStandardInput=true;//重定向标准输出
MyProcess.StartInfo.RedirectStandardOutput=true;//重定向错误输出
MyProcess.StartInfo.RedirectStandardError=true;//设置不显示窗口
MyProcess.StartInfo.CreateNoWindow=true;//执行强制结束命令
MyProcess.Start();
MyProcess.StandardInput.WriteLine("ntsd -c q -p "+(MyProcess1[0].Id).ToString());//直接结束进程ID
MyProcess.StandardInput.WriteLine("Exit");
第二种,通过强大的进程类进行标准关闭。
string ProcessName="explorer";//换成想要结束的进程名字
Process[] MyProcess=Process.GetProcessesByName(ProcessName);
MyProcess[0].Kill();

 

客户端调用 CMD 命令并回显结果。,布布扣,bubuko.com

客户端调用 CMD 命令并回显结果。

标签:style   class   blog   code   tar   ext   

原文地址:http://www.cnblogs.com/gordensong/p/3799808.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!