Create cmd window and write to it from C # app

I am developing a C # component for Grasshopper for Rhino. Since I am running a rather heavy iterative analysis, I would like to output the results continuously in the CMD window to make sure that the analysis is actually running.

Here's what I've tried:

using System.Diagnostics;


Result results = new Result();
Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.RedirectStandardInput = true;
cmd.StartInfo.RedirectStandardOutput = true;
cmd.StartInfo.CreateNoWindow = false;
cmd.StartInfo.UseShellExecute = false;
cmd.Start();

do {
    results = RunHeavyOperation(results);
    cmd.StandardInput.WriteLine("echo " + results.usefulInfo);
} while (!results.conditionForEnd);

cmd.WaitForExit();

Result RunHeavyOperation(Result previousResults) {
    Result res = doHeavyStuff(previousResults);
    return res;
}

      

I understand that I am missing a part, but what is it?

+4


source to share


2 answers


Your approach is wrong: you are not currently writing to the console window. Instead, you created a process by starting cmd.exe

and writing to that process's standard input. cmd.exe

does not know about it. This is not the same as typing on the console through the keyboard, and even that can have strange consequences.
Imagine you are printing a newline, so it cmd.exe

might try to "execute" what you previously output as a command.

The correct way is to call . With this call, you can create a console window for your process and use it simply via . AllocConsole

Console.WriteLine()

When you are done with your work and system, you will eventually need to close and release that console again via . FreeConsole

FreeConsole

So, import these two native methods:

internal sealed class NativeMethods
{
    [DllImport("kernel32.dll")]
    public static extern bool AllocConsole();

    [DllImport("kernel32.dll")]
    public static extern bool FreeConsole();
}

      



And use them in your code:

NativeMethods.AllocConsole();

// start work
Console.WriteLine("log messages...");

// finished work

NativeMethods.FreeConsole();

      


Note that this FreeConsole()

will close the console window so all your log messages will be lost. And the console only has such a large buffer, and you can't scroll back to older messages if you leave the buffer behind.

So it might be better to just write your log messages to a file that you can analyze later.

+6


source


Create a Console Application in Visual Studio. In VS 2017 it looks like this (on the start page):

enter image description here

Console applications automatically open the console. Then you can write with



Console.WriteLine("hello");

      

The console closes automatically when the program exits. So don't forget to call Console.ReadKey();

at the end if you want it open.

0


source







All Articles