tags:

views:

400

answers:

3

I am trying to write my own Command Line wrapper like 'Console2' in C#. Unfortunately I haven't figured out a good way to do it.

Can somebody give me an example of grabbing console input and output and directing it into an Application?

NB I am not trying to make a console application, I am trying to make a wrapper for console - A windows forms application with a richtextedit which acts like a console and which can handle IO like Windows Console

A: 
public static class Console2
{
    public void WriteLine(object o)
    {
        //do stuff?
        Console.WriteLine(o);
    }
    public string ReadLine(object o)
    {
        //do stuff?
        return Console.ReadLine();
    }
}
Paul Creasey
+3  A: 

You should start cmd.exe with Process class and user ProcessStartInfo class to get a hold of StandardInput, StandardOutput and StandardError streams.

Read more about ProcessStartInfo class on MSDN.

Also, there is a nice sample project at CodeProject..

And Console2 is an open source project, so you can take a look at its code. I know it's C++ but you still get some ideas from looking at the source.

David Vidmar
StandardOutput idea didn't work. It allows you to get the output after the process exectuted. All the user input is ignored.
Nick Brooks
+1  A: 

You cannot reliably get all console output from a process by only redirecting its standard handles. As soon as it uses raw console I/O functions, these will only work with a real console and not file handles.

Normally, the default, unredirected STD_INPUT_HANDLE, STD_OUTPUT_HANDLE and STD_ERROR_HANDLE are only pseudo-handles, as in the sense of not being handles known to the NT kernel for that process. The ReadFile and WriteFile APIs have a hack in them that checks for these pseudo-handles and redirects the call to ReadConsoleA and WriteConsoleA as appropriate. However, all the console APIs only operate on console pseudo-handles (named console input buffers and console screen buffers) and will fail when passed a real file handle.

Now, because of this redirection, and the fact that most programs use the file APIs when writing to or reading from the console means that it is possible to have some level of redirection, but since what you want to do is a complete console emulator, this will not be enough. You will not be able to capture any of the calls that, for example, change the size or attributes of the screen buffer, reads from it, creates alternate ones, etc.

If you are not scared of assembly language and reverse-engineering, you can look into hooking the various console APIs into the target process (and their children), or, in the case of Windows 7, reimplementing conhost.exe.

Koro