Console window does not appear when redirecting output

I am using the following code from a .NET 4 console application:

private static void AttachToConsole () { System.Diagnostics.Process process = null; process = new Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = false; process.EnableRaisingEvents = true; process.Start(); process.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived); Console.Write("Press any key to continue..."); Console.ReadKey(); process.OutputDataReceived -= new DataReceivedEventHandler(Process_OutputDataReceived); process.CloseMainWindow(); process.Close(); } 

At startup, only the console window of the application itself appears, but the process window [cmd.exe] remains invisible. Why is this and how can I change this behavior?

+4
source share
2 answers

if you set UseShellExecute = true , the cmd process window will appear. You will need to set RedirectStandardInput and RedirectStandardpOutput to "false" (or comment on them).

 private static void AttachToConsole () { System.Diagnostics.Process process = null; process = new Process(); process.StartInfo.FileName = "cmd.exe"; //process.StartInfo.RedirectStandardInput = true; //process.StartInfo.RedirectStandardOutput = true; process.StartInfo.UseShellExecute = true; process.StartInfo.CreateNoWindow = false; process.EnableRaisingEvents = true; process.Start(); process.OutputDataReceived += null; Console.Write("Press any key to continue..."); Console.ReadKey(); process.OutputDataReceived -= null; process.CloseMainWindow(); process.Close(); } 
+2
source

I really don't know how to fix this, but I know why this works.

You set

UseShellExecute=false;

The core of cmd.exe is equal to the Windows Command Processor , so executing using the Windows shell creates new console windows that are terminals, whose input is processed by cmd.exe, and the output is sent to the terminal.

If you set UseShellExecute=true , a window will appear, but you cannot redirect input and output, and this is due to how it works, as I described in the previous paragraph

EDIT: The most important part: you wrote the "process window"; Console type processes do not have WINDOW at all

+2
source

Source: https://habr.com/ru/post/1486077/


All Articles