I need an Windows Forms application with the below behavior:
- Work without any console when program is running from explorer (for example).
- Redirect all text from
Console.WriteLine()
when program is running from a command line (so program must to redirect all output to a parrent console)
For this purpose is suitable the following code:
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[STAThread]
static void Main()
{
AttachConsole(-1);
Console.WriteLine("Test1");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.WriteLine("WinForms exit");
}
But here is one problem: When the form is opened and a user closes the console, then my program automatically closes. I need to leave program running after user closes console. I tried to use SetConsoleCtrlHandler()
and in the handler call FreeConsole()
but all the same the program closes after calling handler:
static class Program
{
[DllImport("Kernel32")]
public static extern bool SetConsoleCtrlHandler(HandlerRoutine Handler, bool Add);
// A delegate type to be used as the handler routine
// for SetConsoleCtrlHandler.
public delegate bool HandlerRoutine(CtrlTypes CtrlType);
private static bool ConsoleCtrlCheck(CtrlTypes ctrlType)
{
Console.OutputEncoding = Console.OutputEncoding;
FreeConsole();
return true;
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool FreeConsole();
[STAThread]
static void Main()
{
AttachConsole(-1);
SetConsoleCtrlHandler(ConsoleCtrlCheck, true);
Console.WriteLine("Test1");
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
Console.WriteLine("WinForms exit");
}
// An enumerated type for the control messages
// sent to the handler routine.
public enum CtrlTypes
{
CTRL_C_EVENT = 0,
CTRL_BREAK_EVENT,
CTRL_CLOSE_EVENT,
CTRL_LOGOFF_EVENT = 5,
CTRL_SHUTDOWN_EVENT
}
}
How to prevent closing Windows Forms application when user closes console?