5

I know this question has been asked previously and I have tried all the solutions given in those posts before but I can't seem to make it work:-

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();
        }

When I try to call the batch file, it still shows the window even though createNoWindow and UseShellExecute are both set to true.

Should I put something else to make it run the batch file silently?

user1439090
  • 792
  • 5
  • 12
  • 33

1 Answers1

9

Try this:

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;

The idea is to not manipulate myProcess.StartInfo after you have started your process: it is useless. Also you do not need to set UseShellExecute to true, because you are starting the shell yourself by calling cmd.exe.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • When I replace it with this code, a cmd window appears and the application just stops. These is no output on the window. – user1439090 Sep 19 '12 at 02:32
  • @user1439090 Very curious... Did you try setting `path` for the `FileName`, bypassing `cmd` altogether, or is it a batch file that you're trying to run? – Sergey Kalinichenko Sep 19 '12 at 02:34
  • path is the path to the batch file. In my case, the batch file is present in the same folder as exe so I am simply passing the name of the batch file as the argument. – user1439090 Sep 19 '12 at 02:41
  • oh I removed a pause that was there in my batch file and it started working silently. This is after replacing my code with the code suggested by dasblinkenlight. Thanks for the help. On the side note, is this behaviour due to the fact that "pause" in batch file forces user to press some key? – user1439090 Sep 19 '12 at 02:50
  • @user1439090 What you described makes perfect sense: I think this is because `pause` looks for user input, so the operating system brings up the window. – Sergey Kalinichenko Sep 19 '12 at 02:57