Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate a console for a WinForm application

I use the following code to allocate a Console for a WinForm application. The Console window shows up successfully and the output is there. But when I close the Console window, my WinForm applicaion is closed at the same time. Why? I want to keep the WinForm window.

private void btn_to_console_Click(object sender, EventArgs e)
{
    if (NativeMethods.AllocConsole())
    {
        lbl_console_alloc_result.Text = "Console allocation successfully!";
        IntPtr stdHandle = NativeMethods.GetStdHandle(NativeMethods.STD_OUTPUT_HANDLE);
        Console.WriteLine("from WinForm to Console!");
        lbl_console_alloc_result.Text = Console.ReadLine();
    }
    else
        lbl_console_alloc_result.Text = "Console allocation failed!";
}

[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "GetStdHandle")]
public static extern System.IntPtr GetStdHandle(Int32 nStdHandle);

/// Return Type: BOOL->int
[System.Runtime.InteropServices.DllImportAttribute("kernel32.dll", EntryPoint = "AllocConsole")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool AllocConsole();

Thanks in advance...

like image 247
smwikipedia Avatar asked Feb 27 '10 17:02

smwikipedia


1 Answers

Closing a Console Window will shutdown any application -whether a console application, Windows Forms, native Windows app, or WPF application. This is a "feature" of Console windows.

If you don't want this behavior, you should, instead, just make a custom window to display your output instead of using a Console Window. Otherwise, you need to call FreeConsole instead of closing the Window to detach your application from the Console window.

like image 51
Reed Copsey Avatar answered Oct 21 '22 06:10

Reed Copsey