Add this functions somewhere in a class to your project:
(requires a using System.Runtime.InteropServices;
on top of the class)
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32.dll")]
private static extern bool FreeConsole();
Then call AttachConsole(-1)
Now you can use the System.Console class as usual to write to the console and set colors and whatnot.
If you no longer need to write to the console, call FreeConsole()
to detach your process from it.
Be aware that this does not actually blocks the console from processing further commands. The user is still allowed to enter anything into the console at anytime.
The recommended way is as follows:
- Create a console application
- Write to it whatever you want.
- Call
FreeConsole()
once you no longer need it.
- Open your form using
Application.Run()
. Not using application.Run and only showing the form does not creates a proper message loop and strange things can happen.
You can switch 3 and 4, but as soon as you call the Application.Run
method, the code will not continue until the form is closed. So either write to the console in the form and free it from there or spawn the form in a separate thread (which has other unintended side consequences)
You can supply any process ID to the AttachConsole function. -1 default to the parent process which is most likely what you want.