A
A
Alexander Antonov2016-03-07 09:00:38
cmd/bat
Alexander Antonov, 2016-03-07 09:00:38

How to get cmd.exe output with color preserved?

The problem is that through the construct:

cmdProcess = new Process();
var procStartInfo = new ProcessStartInfo( "cmd", "/k \"C:\\Program Files (x86)\\Far Manager\\Far.exe\"" );

procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardInput = true;
procStartInfo.UseShellExecute = false;

procStartInfo.CreateNoWindow = true;
cmdProcess.OutputDataReceived += ( s, e ) => {
       callbackFn(e.Data + "\n");
};
cmdProcess.StartInfo = procStartInfo;

cmdProcess.Start();
cmdProcess.BeginOutputReadLine();

Can't get color and can't get output from far manager. I couldn't figure it out with winAPi - just create a process.
I tried with ReadConsoleOutput but I end up with only an empty buffer.
Can you tell me how to get a normal output?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Antonov, 2016-03-08
@undermuz

Figured it out myself, example code:

ConsoleApi.PROCESS_INFORMATION _p = ConsoleApi.createConsoleTerminal(command);

            Thread.Sleep(1000);

            bool resultFree = ConsoleApi.FreeConsole();

            if (resultFree)
            {
                Debug.WriteLine("FreeConsole: {0}", true);
            }
            else
            {
                Debug.WriteLine("FreeConsole: {0}", false);
            }

            Debug.WriteLine("Process ID: {0}", _p.dwProcessId);

            bool result = ConsoleApi.AttachConsole(_p.dwProcessId);

            Debug.WriteLine("AttachConsole: {0}", result);

            IntPtr _consoleH = ConsoleApi.GetStdHandle(ConsoleApi.STD_OUTPUT_HANDLE);

            ConsoleApi.CONSOLE_SCREEN_BUFFER_INFO _bufferInfo;

            bool getInfo = ConsoleApi.GetConsoleScreenBufferInfo(_consoleH, out _bufferInfo);

            if (getInfo)
            {
                Debug.WriteLine("GetConsoleScreenBufferInfo: {0}x{1}", _bufferInfo.dwSize.X, _bufferInfo.dwSize.Y);
            }
            else
            {
                Debug.WriteLine("GetConsoleScreenBufferInfo: {0}", false);
            }

            while(true)
            {
                IEnumerable<string> rows = ConsoleApi.ReadFromBuffer(_consoleH, 0, 0, _bufferInfo.dwSize.X, _bufferInfo.dwSize.Y);

                foreach (string row in rows)
                {
                    Debug.WriteLine(row);
                }

                Thread.Sleep(1000);
            }

V
Valery Okhotnikov, 2016-03-07
@vox13

You start a "cmd.exe" shell and then tell it to run Far, then read the output of "cmd.exe".
Why not run Far right away and read its output?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question