pmuench
pmuench

Reputation: 15

When executing a batch file from c# with the window hidden, programs that are executed by the batch file won't start

I'm trying to write a small tool (called StartProcess.exe) in C# that allows me to execute batch files without the cmd window showing. It uses the following code (excerpt from Main()):

        Process process = new Process();

        // Stop the process from opening a new window
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardError = true;
        process.StartInfo.UseShellExecute = false;
        process.StartInfo.CreateNoWindow = true;

        // Setup executable and parameters
        process.StartInfo.FileName = args[0];

        // Go
        process.Start();

Unfortunately, this does not work as intended. When I try to use the tool in a shortcut on the desktop to execute a small batch file (test.bat) that tries to start notepad, nothing happens. When I try StartProcess notepad on a cmd prompt, it works.

Does anybody know or have an educated guess what could be causing this behaviour?

Upvotes: 0

Views: 2136

Answers (2)

Jauch
Jauch

Reputation: 1518

This works perfectly for me when using a "console application" and with "windows application", using DotNet 4 Client Profile.

Process process = new Process();

// Stop the process from opening a new window
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;

// Setup executable and parameters
process.StartInfo.FileName = "batch.bat";

// Go
process.Start();

where batch.bat is in the same folder my program and contains just a line:

notepad

And when my program end, the notepad is still open...

If you change your application from "Console Application" for "Windows Application", the above code seems to not work. But if you add Thread.Sleep(1000); at the end, after the process.Start();, it works as expected. The Nopepad is opened and the program finishes.

Upvotes: 1

pmuench
pmuench

Reputation: 15

I found the solution myself. My tool exits directly after process.Start() and simultaneously kills all its child processes. When adding a process.WaitForExit()after the process.Start(), it works as expected.

Note: as you can see from the answers below, this seems to be needed only when compiling as a "Windows Application".

    Process process = new Process();

    // Stop the process from opening a new window
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.CreateNoWindow = true;

    // Setup executable and parameters
    process.StartInfo.FileName = args[0];

    // Go
    process.Start();
    process.WaitForExit();

Upvotes: 1

Related Questions