【发布时间】:2010-11-08 22:57:02
【问题描述】:
如何在运行批处理文件时隐藏 cmd 窗口?
我使用下面的代码来运行批处理文件
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
【问题讨论】:
标签: c# process batch-file
如何在运行批处理文件时隐藏 cmd 窗口?
我使用下面的代码来运行批处理文件
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
【问题讨论】:
标签: c# process batch-file
如果 proc.StartInfo.UseShellExecute 为 false,那么您正在启动进程并且可以使用:
proc.StartInfo.CreateNoWindow = true;
如果 proc.StartInfo.UseShellExecute 为 true,则操作系统正在启动进程,您必须通过以下方式向进程提供“提示”:
proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
但是被调用的应用程序可能会忽略后一个请求。
如果使用 UseShellExecute = false,您可能需要考虑重定向标准输出/错误,以捕获生成的任何日志记录:
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
proc.StartInfo.RedirectStandardError = true;
proc.ErrorDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
并且有类似的功能
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
an MSDN blog 上有一个很好的页面覆盖 CreateNoWindow 这个。
Windows 中还有一个错误,如果您传递用户名/密码,可能会引发对话框并破坏CreateNoWindow。详情
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476 http://support.microsoft.com/?kbid=818858
【讨论】:
根据Process properties,您确实有:
属性:
CreateNoWindow
注意:允许您以静默方式运行命令行程序。 它不会闪烁控制台窗口。
和:
属性:
WindowStyle
注意:使用它可以将窗口设置为隐藏。 作者经常使用ProcessWindowStyle.Hidden。
举个例子!
static void LaunchCommandLineApp()
{
// For the example
const string ex1 = "C:\\";
const string ex2 = "C:\\Dir";
// Use ProcessStartInfo class
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;
startInfo.UseShellExecute = false;
startInfo.FileName = "dcm2jpg.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;
try
{
// Start the process with the info we specified.
// Call WaitForExit and then the using statement will close.
using (Process exeProcess = Process.Start(startInfo))
{
exeProcess.WaitForExit();
}
}
catch
{
// Log error.
}
}
【讨论】:
使用: process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
【讨论】:
这对我有用, 当您重定向所有输入和输出并将窗口设置为隐藏时,它应该可以工作
Process p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
【讨论】: