Is it possible to log message from WinForms app to cmd.exe process started programmatically? I've tried to do all kinds of variations of following code:
private void button1_Click(object sender, EventArgs e)
{
Log("Button has been pressed");
}
private void Log(string message)
{
var process = Process.Start(new ProcessStartInfo("cmd.exe", @"/K ""more""")
{
UseShellExecute = false,
RedirectStandardInput = true,
});
process.StandardInput.WriteLine(message);
}
Unfortunately, console window blinks for a half of a second and that's it.
Please don't answer what I really want to do, because right now I'm just curious if it's possible :)
As far as I know, I believe you get the CMD opened right. But as soon as the command has been executed the console terminates. Thats normal behaviour.
If you execute a .bat/.cmd you could script more than one command and if you made a "pause" after the command, you should be able to see what happend before the console terminates.
You have to insert a pause command after printing to the console.
The process terminates as soon as the command is executing, resulting in the blink you see.
You're in luck. I just solved this for a code generator toy project I had floating around here.
Using
AttachConsole
orAllocConsole
Win32 API's you can achieve the result, by just usingSystem.Console.WriteLine
(or Read, or Error.WriteLine etc) like you normally would.The following snippet figures out when a forms app was started from a Console window, and attaches to it's parent console; If that doesn't work, it will create it's own console, and remember to keep it open (so it doesn't vanish before the user can read the output, for example).
Not the final answer, but it should help at least a little:
First of all, declare that process outside your Log routine so it doesn't go out of scope when you want to log more.
Anyway I tried the following:
After clicking the button, your app will hang (it's waiting for the console to close, ReadToEnd literally reads to the end). When you close the console you will get a messagebox with the error output:
It seems not to be possible to redirect only the input without redirecting the output when running CMD. I'm not sure why, maybe trying different commandline options will help. I also tried removing the More command and logging "dir" instead:
The result was a bit scary:
Interesting I must say! Looks like you've opened a can of worms :-)
I think if you build your project as a "Console Application", you get the console and can still open Windows forms. Create a new project of type "Console Application". Add a Windows Form to the project. In the Main function in Program.cs, instantiate and display the form using this code:
Am not sure if this is the ideal way to do it. But it works.