如何在运行批处理文件时隐藏cmd窗口?
如何在运行批处理文件时隐藏cmd窗口?
我使用以下代码来运行批处理文件
process = new Process(); process.StartInfo.FileName = batchFilePath; process.Start();
如果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);
并且具有类似的function
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow; }
在MSDN博客上有一个很好的页面覆盖了CreateNoWindow
。
Windows中还有一个错误,如果您传递用户名/密码,可能会抛出一个对话框并击败CreateNoWindow
。 详情
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476 http://support.microsoft.com/?kbid=818858
根据Process属性 ,您有一个:
属性:
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 = "-fj -o \"" + ex1 + "\" -z 1.0 -sy " + 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;