【问题标题】:Allocate a console for a WinForm application为 WinForm 应用程序分配控制台
【发布时间】:2011-01-21 20:03:22
【问题描述】:

我使用以下代码为 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();

提前谢谢...

【问题讨论】:

标签: c# operating-system


【解决方案1】:

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

如果您不希望这种行为,您应该改为创建一个自定义窗口来显示您的输出,而不是使用控制台窗口。否则,您需要调用FreeConsole 而不是关闭窗口以将您的应用程序与控制台窗口分离。

【讨论】:

  • 谢谢,里德,谢谢。看来我需要一本关于 Win32 API 的字典。:D
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-04
相关资源
最近更新 更多