这是一个有点复杂的问题。我尝试了所有的东西,但仍然没有工作。我从运行CMD运行WinForm应用程序,然后在cmd上运行另一个应用程序(控制台应用程序)。它正在/c START xyz
上工作,但当应用程序完成时,CMD始终关闭。我想暂停这个窗口。
ProcessStartInfo processInfo = new ProcessStartInfo {
FileName = "cmd.exe",
WorkingDirectory = Path.GetDirectoryName(YourApplicationPath),
Arguments = "/K START " + cmdparametr,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = false,
UseShellExecute = false,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal,
};
Process p = new Process {
StartInfo = processInfo
};
p.Start();
int ExitCode;
p.WaitForExit();
// *** Read the streams ***
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
ExitCode = p.ExitCode;
MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
p.Close();
当我添加参数ReadStream
时, START /b
正在工作,但我认为这并不重要。
WaitForExit()
不起作用。
是否可以通过命令暂停应用程序,如下所示:
/k start xyz.exe & PAUSE
?
我的应用是控制台应用程序!
答案 0 :(得分:2)
如果需要,可以在C#中使用pause
- 命令:
我用它如下:
解决方案№1:
//optional: Console.WriteLine("Press any key ...");
Console.ReadLine(true);
解决方案№2: (使用P / Invoke)
// somewhere in your class
[DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl, SetLastError=true)]
public static extern int system(string command);
public static int Main(string[] argv)
{
// your code
system("pause"); // will automaticly print the localized string and wait for any user key to be pressed
return 0;
}
<小时/> 编辑:您可以动态创建临时批处理文件并执行它,例如:
string bat_path = "%temp%/temporary_file.bat";
string command = "command to be executed incl. arguments";
using (FileStream fs = new FileStream(bat_path, FileMode.OpenOrCreate, FileAccess.Write, FileShare.Read))
using (StreamWriter sw = new StreamWriter(fs, Encoding.Default))
{
sw.WriteLine("@echo off");
sw.WriteLine(command);
sw.WriteLine("PAUSE");
}
ProcessStartInfo psi = new ProcessStartInfo() {
WorkingDirectory = Path.GetDirectoryName(YourApplicationPath),
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
CreateNoWindow = false,
UseShellExecute = false,
WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal
};
Process p = new Process() {
StartInfo = psi;
};
p.Start();
int ExitCode;
p.WaitForExit();
// *** Read the streams ***
string output = p.StandardOutput.ReadToEnd();
string error = p.StandardError.ReadToEnd();
ExitCode = p.ExitCode;
MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
p.Close();
File.Delete(bat_path);
答案 1 :(得分:1)
为防止关闭控制台应用程序,您可以使用:
or
它会等待任何键,不会立即关闭。
答案 2 :(得分:1)
不要包含START
命令,请使用类似
processInfo.Arguments = "/K " + your_console_app_exe_path_and_args;
确保在需要时用双引号括起来。