using System.Diagnostics;
using System.Windows.Forms;
using System.Collections;
namespace C17_1
{
public class Program
{
///
///運行cmd命令
///
///命令
///
public static string Cmd(string[] cmd)
{
foreach(string a in cmd)
{
Console.WriteLine(a);
}
Process p = new Process();
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());
}
p.StandardInput.WriteLine("exit");
string result = p.StandardOutput.ReadToEnd();
p.WaitForExit();
p.Close();
return result;
}
///
///關閉處理序
///
///處理序名稱
///
public static bool CloseProcess(string ProcName)
{
bool result = false;
ArrayList pList = new ArrayList();
string tempName = "";
int begpos;
int endpos;
foreach(Process p in Process.GetProcesses())
{
tempName = p.ToString();
begpos = tempName.IndexOf("(")+1;
endpos = tempName.IndexOf(")");
tempName = tempName.Substring(begpos,endpos-begpos);
pList.Add(tempName);
if (tempName == ProcName)
{
if (!p.CloseMainWindow())
{
//當發送關閉視窗命令無效時強行結束處理序
p.Kill();
}
result = true;
}
}
return result;
}
public static void Main()
{
string[] cmd = new string[] {"ping 192.168.1.1","ipconfig" };
MessageBox.Show(Cmd(cmd));
CloseProcess("cmd.exe");
}
}
}
沒有留言:
張貼留言