Ultron.Ngrok/Ultron.Ngrok/Utils/CmdUtils.cs

101 lines
3.2 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Ultron.Ngrok.Utils
{
public class CmdUtils
{
public delegate void ProcessInfomation(int id, string message);
public event ProcessInfomation ProcessMessageEvent;
public event EventHandler ProcessKilled;
Process cmd = new Process();
public bool IsInited = false;
public CmdUtils()
{
Control.CheckForIllegalCrossThreadCalls = false;
}
public void Init()
{
cmd = new Process();//创建进程对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";//设定需要执行的命令
startInfo.Arguments = "";//“/C”表示执行完命令后马上退出
startInfo.UseShellExecute = false;//不使用系统外壳程序启动
startInfo.RedirectStandardInput = true;//不重定向输入
startInfo.RedirectStandardOutput = true; //重定向输出
startInfo.CreateNoWindow = false;//不创建窗口
cmd.StartInfo = startInfo;
cmd.EnableRaisingEvents = true;
cmd.OutputDataReceived -= new DataReceivedEventHandler(OutputHandler);
cmd.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
cmd.Exited += ProcessKilled;
cmd.Start();
cmd.BeginOutputReadLine();
}
void cmd_Exited(object sender, EventArgs e)
{
}
private void OutputHandler(object sender, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
ProcessMessageEvent(cmd.Id, e.Data);
}
}
public void SendMsg(string cmdStr)
{
ProcessMessageEvent(0, "开始运行...");
if (!IsInited || cmd.HasExited)
{
cmd = new Process();//创建进程对象
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";//设定需要执行的命令
startInfo.Arguments = "";//“/C”表示执行完命令后马上退出
startInfo.UseShellExecute = false;//不使用系统外壳程序启动
startInfo.RedirectStandardInput = true;//不重定向输入
startInfo.RedirectStandardOutput = true; //重定向输出
startInfo.CreateNoWindow = false;//不创建窗口
cmd.StartInfo = startInfo;
cmd.EnableRaisingEvents = true;
cmd.OutputDataReceived -= new DataReceivedEventHandler(OutputHandler);
cmd.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
cmd.Exited += ProcessKilled;
cmd.Start();
cmd.BeginOutputReadLine();
IsInited = true;
}
cmd.StandardInput.WriteLine(cmdStr);
}
public void CloseCmd()
{
if (cmd != null && !cmd.HasExited)
cmd.Kill() ;
}
}
}