16

I'm writing a basic shell for Windows, and I was wondering if there is any way to run a subprocess (Process process) so that it uses the current console window. By this I mean that I do not want to redirect input/output; I want the process to take input from the current console and print output directly to the same console window.

The reason is that I want to allow this subprocess to set console colors for output, which cannot happen if I redirect the process' standard output. Also, I currently use the code

while (!process.HasExited)
    process.StandardInput.WriteLine(Console.ReadLine());

to redirect standard input to the process. However, if the process exits immediately after an input (for example, I type "exit" + ENTER, and the process exits), this loop will run once more, so the console is waiting for input from the user that will never be used by the process (it is about to exit).

So, long question short, how do I run a process in the current console, so that it can set console colors and directly take input from the console?

Edit: Below are the methods that are relevant to this question from my code:

static int runExe(string exePath, params string[] args)
{
    ProcessStartInfo startInfo = new ProcessStartInfo(exePath, args)
    {
        ErrorDialog = false,
        UseShellExecute = false,
        CreateNoWindow = true,
        RedirectStandardInput = true,
        RedirectStandardOutput = true,
        RedirectStandardError = true,
        RedirectStandardInput = true
    };
    Process process = new Process() { StartInfo = startInfo };
    process.Start();
    ReadThreadState stdout = readThread(process.StandardOutput, false);
    ReadThreadState stderr = readThread(process.StandardError, true);
    while (!process.HasExited)
        process.StandardInput.WriteLine(Console.ReadLine());
    stdout.stop = stderr.stop = true;
    return process.ExitCode;
}
class ReadThreadState
{
    public bool stop;
}
private static ReadThreadState readThread(StreamReader reader, bool isError)
{
    ReadThreadState state = new ReadThreadState();
    new Thread(() =>
    {
        while (!state.stop)
        {
            int current;
            while ((current = reader.Read()) >= 0)
                if (isError)
                    writeError(((char)current).ToString(), ConsoleColor.Red);
                else
                    Console.Write((char)current);
        }
    }).Start();
    return state;
}
5
  • Try to experiment with /c option of cmd.exe. Like Process.Start("cmd.exe", "YOURAPP.exe /c");
    – Anri
    Jul 19, 2013 at 17:25
  • @Anri I don't think that's what I need; I don't want to run it through cmd.exe.
    – feralin
    Jul 19, 2013 at 17:25
  • it barely makes a difference to start console app through cmd or not
    – Anri
    Jul 19, 2013 at 17:27
  • This requirement is a bit of a red flag. It means that the other application should probably be a .dll that you reference in your program, rather than another executable program.
    – Servy
    Jul 19, 2013 at 18:14
  • @Servy I'm writing a command shell that has color. If I type "shell" ENTER from the shell, then the subshell does not have color. I want it to. However, I cannot reference every .dll for every program the shell will run; some programs may not even be .NET programs...
    – feralin
    Jul 19, 2013 at 18:17

2 Answers 2

24

You need to create a ProcessStartInfo and set UseShellExecute to false:

var info = new ProcessStartInfo("program.exe", "arguments");
info.UseShellExecute = false;
var proc = Process.Start(info);
proc.WaitForExit();

That will start your program in the same console.

Working program that uses the above technique:

private static void Main(string[] args)
{
    Console.WriteLine("Starting program");
    var saveColor = Console.BackgroundColor;
    Console.BackgroundColor = ConsoleColor.Blue;
    var info = new ProcessStartInfo("cmd", "/c time");
    info.UseShellExecute = false;
    var proc = Process.Start(info);
    proc.WaitForExit();

    Console.BackgroundColor = saveColor;
    Console.WriteLine("Program exited");
    Console.ReadLine();
}

When you run the program, it starts a new copy of cmd.exe and runs the time command, which asks for input. I just used cmd.exe as an example here to illustrate. Any program that reads from standard input will work. Note also that the console colors work correctly.

5
  • I've already done that (perhaps I should post more of my code), and the child process never asks for input from the console. This is not the answer :(
    – feralin
    Jul 19, 2013 at 18:11
  • @feralin: You might want to give my example a try. I don't know what you did, but my sample does what you said you want to do. Jul 19, 2013 at 18:29
  • @feralin: You asked: "how do I run a process in the current console, so that it can set console colors and directly take input from the console?" My example does exactly that. Jul 19, 2013 at 18:36
  • you know, you're right. I could've sworn I tried this earlier, but I guess I didn't. My bad :(. Your answer is correct.
    – feralin
    Jul 19, 2013 at 18:39
  • 1
    Also note the (implicit) default of CreateNoWindow=false vs the explicit true in the OP code. Gem of an answer here. Apr 20, 2014 at 3:11
2

Jim Mischel's answer works like a charm. I'm moving some batch file processing into C# and that works great. You may find this small utility method handy. Just takes a command line, and runs it just like CALL in a batch file. Just stuff it in a utility class:

public static void RunCmd(string command) {
    Process.Start(new ProcessStartInfo("cmd.exe", "/c " + command) {
        UseShellExecute = false
    }).WaitForExit();            
}    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.