Reputation: 14777
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();
}
When run, only the console window of the app itself shows up but the [cmd.exe]
process window remains invisible. Why is that and how can I change this behavior?
Upvotes: 5
Views: 2122
Reputation: 4733
I don't really know how to fix it but I know why it works like that.
You set
UseShellExecute=false;
well cmd.exe
is Windows Command Processor
so executing with windows shell creates new console windows which is terminal whose input is processed by the cmd.exe and output is directed to the terminal.
If you set UseShellExecute=true
the window will show but you won't be able to redirect input and output and this is because of the way it works as I described in above paragraph
EDIT: The most important part: you wrote "the process window"; console type procesesses have NO WINDOW at all
Upvotes: 2
Reputation: 305
if you set UseShellExecute = true
the cmd process window will appear. You wil need to set RedirectStandardInput and RedirectStandardpOutput to 'false' (or comment them out) however.
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();
}
Upvotes: 2