I have a WinForm project that I want to be usable as a console app if certain arguments are passed into it. Using some tips I read from here, I used the following code to make this work.
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
...
if (!AttachConsole(-1))
{
AllocConsole();
}
This works, but there is one annoying side effect - all the output seems to be generated from a background thread. When I run the program from a command prompt, the output displays the next prompt before displaying the output.
I set the project properties' Output Type to Console Application and it fixed this problem, but now there is always a console window displayed - even when it is run in 'WinForm mode'.
Is there a way to get the best of both worlds where the console behaves like the program is the current process and the console window is not displayed when the program displays the WinForm?
UPDATE: My apologies for not clarifying this. I am toggling between console and WinForm mode in Program.cs like this:
// nowin is a bool that is set based on a parameter
if (nowin)
{
if (!AttachConsole(-1))
{
AllocConsole();
}
//... Console mode code here...
}
else
{
// run in window
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(argDict));
}