繁体   English   中英

为WinForm应用程序分配控制台

[英]Allocate a console for a WinForm application

我使用以下代码为WinForm应用程序分配控制台。 控制台窗口成功显示,输出就在那里。 但是当我关闭控制台窗口时,我的WinForm应用程序同时关闭。 为什么? 我想保留WinForm窗口。

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();

提前致谢...

关闭控制台窗口将关闭任何应用程序 - 无论是控制台应用程序,Windows窗体,本机Windows应用程序还是WPF应用程序。 这是控制台窗口的“功能”。

如果您不想要此行为,则应该只创建一个自定义窗口来显示输出,而不是使用控制台窗口。 否则,您需要调用FreeConsole而不是关闭Window以从Console窗口中分离您的应用程序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM