如何在运行批处理文件时隐藏cmd窗口?
我使用以下代码来运行批处理文件:
process = new Process();
process.StartInfo.FileName = batchFilePath;
process.Start();
如何在运行批处理文件时隐藏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);
并且有一个像这样的函数
private void ProcessOutputHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
if (!String.IsNullOrEmpty(outLine.Data)) // use the output outLine.Data somehow;
}
这个MSDN博客页面提供了关于CreateNoWindow
的详细介绍。
同时,在Windows中也存在一个bug,如果你传递了用户名和密码,可能会弹出对话框并阻止CreateNoWindow
的功能。有关详细信息,请参见:
http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98476 http://support.microsoft.com/?kbid=818858
属性:
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 p = new Process();
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;