从C#中静默执行批处理文件

5

我知道这个问题之前已经被问过了,我也在之前的帖子中尝试了所有给出的解决方案,但似乎都不能使其正常工作:

static void CallBatch(string path)
        {
            int ExitCode;
            Process myProcess;

            ProcessStartInfo ProcessInfo;
            ProcessInfo = new ProcessStartInfo("cmd.exe", "/c " + path);
            ProcessInfo.CreateNoWindow = true;
            ProcessInfo.UseShellExecute = true;

            myProcess = Process.Start(ProcessInfo);
            myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            myProcess.WaitForExit();

            myProcess.EnableRaisingEvents = true;
            myProcess.Exited += new EventHandler(process_Exited);

            ExitCode = myProcess.ExitCode;

            Console.WriteLine("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
            myProcess.Close();
        }

当我尝试调用批处理文件时,即使createNoWindow和UseShellExecute都设置为true,它仍然显示窗口。我应该加入其他内容使其静默运行批处理文件吗?
1个回答

9

试试这个:

Process myProcess = new Process();
myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcess.StartInfo.CreateNoWindow = true;
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.FileName = "cmd.exe";
myProcess.StartInfo.Arguments = "/c " + path;
myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(process_Exited);
myProcess.Start();
myProcess.WaitForExit();
ExitCode = myProcess.ExitCode;

在启动进程后,不要再操纵myProcess.StartInfo,这是无用的。同时,您不需要将UseShellExecute设置为true,因为您通过调用cmd.exe自己启动了shell。


当我用这段代码替换它时,一个cmd窗口出现了,应用程序就停止了。窗口上没有任何输出。 - user1439090
@user1439090 非常好奇...您是否尝试为FileName设置path,完全绕过cmd,或者您正在尝试运行批处理文件? - Sergey Kalinichenko
路径是批处理文件的路径。在我的情况下,批处理文件与exe文件位于同一文件夹中,因此我只需将批处理文件的名称作为参数传递即可。 - user1439090
我在批处理文件中删除了一个暂停,然后它就开始静默工作了。这是在使用dasblinkenlight建议的代码替换我的代码之后发生的。感谢您的帮助。另外,这种行为是否是因为批处理文件中的“暂停”强制用户按下某个键? - user1439090
@user1439090,你所描述的非常有道理:我认为这是因为pause在寻找用户输入,所以操作系统会弹出窗口。 - Sergey Kalinichenko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接