Writing console output from winforms c # application

Possible duplicate:
How to show console output / window in forms application?

Is there a way to run a C # winforms program in a console window?

+6
c # windows console winforms
source share
1 answer

There are basically two things that can happen here.

  • Console exit

Perhaps the winforms program is attached to the console window that created it (or to another console window, or even to a new console window, if necessary). After connecting to the console window Console.WriteLine (), etc. It works as expected. One of them is that the program immediately returns control to the console window, and then continues to write to it, so the user can also enter the console window. You can use start with the / wait option to handle this, I think.

Link to the beginning of command syntax

  1. Console redirected output

This is when someone transfers the output from your program elsewhere, for example.

yourapp> file.txt

Attaching to the console window in this case effectively ignores the pipeline. To do this, you can call Console.OpenStandardOutput () to get the handle to the stream to which the output should be connected. This only works if the output is transmitted through channels, so if you want to process both scenarios, you need to open the standard output and write to it and attach it to the console window. This means that the output is sent to the console window and to the channel, but this is the best solution I can find. Below is the code I use for this.

// This always writes to the parent console window and also to a redirected stdout if there is one. // It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise // write to the console) but it doesn't seem possible. public class GUIConsoleWriter : IConsoleWriter { [System.Runtime.InteropServices.DllImport("kernel32.dll")] private static extern bool AttachConsole(int dwProcessId); private const int ATTACH_PARENT_PROCESS = -1; StreamWriter _stdOutWriter; // this must be called early in the program public GUIConsoleWriter() { // this needs to happen before attachconsole. // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere // I guess it probably does write somewhere, but nowhere I can find out about var stdout = Console.OpenStandardOutput(); _stdOutWriter = new StreamWriter(stdout); _stdOutWriter.AutoFlush = true; AttachConsole(ATTACH_PARENT_PROCESS); } public void WriteLine(string line) { _stdOutWriter.WriteLine(line); Console.WriteLine(line); } } 
+15
source share

All Articles