我是否可以从带有C sharp的Windows窗体中调用Windows命令,例如在命令提示符中?如果是这样,怎么样?
答案 0 :(得分:2)
最简单的方法是执行以下操作here ..
Process.Start("Executable name here", "parameters here");
但是,如果要设置工作目录,捕获标准输出或错误,请不要创建窗口等。您可以执行以下操作..
void StartNewProcess(string processName, string parameters, string startDir)
{
var proc = new Process();
var args = new ProcessStartInfo
{
FileName = processName,
Arguments = parameters,
WorkingDirectory = startDir,
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
};
proc = Process.Start(args);
proc.ErrorDataReceived += p_DataReceived;
proc.OutputDataReceived += p_DataReceived;
proc.BeginErrorReadLine();
proc.BeginOutputReadLine();
proc.WaitForExit();
}
然后你可以使用类似的东西处理输出..
void p_DataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null && e.Data.Length > 0) Console.WriteLine(e.Data);
}
调用示例..
void button1_Click(object sender, EventArgs e)
{
//Input params: Executable name, parameters, start directory
StartNewProcess("cmd.exe", "/C dir", "C:\\");
}