.net 是否有方法从WinForms/WPF应用程序启动/打开控制台?

.net 是否有方法从WinForms/WPF应用程序启动/打开控制台?,.net,console,.net,Console,我有一个windows窗体应用程序,我想按需打开一个控制台(例如,当我按下按钮时),我可以使用标准控制台类与之交互。有什么方法可以做到这一点吗?是的,有一种方法,您需要在与Win32的互操作上做一些工作 public class ConsoleHelper { public static int Create() { if (AllocConsole()) return 0; else return

我有一个windows窗体应用程序,我想按需打开一个控制台(例如,当我按下按钮时),我可以使用标准控制台类与之交互。有什么方法可以做到这一点吗?

是的,有一种方法,您需要在与Win32的互操作上做一些工作

public class ConsoleHelper
{
    public static int Create()
    {
        if (AllocConsole())
            return 0;
        else
            return Marshal.GetLastWin32Error();
    }

    public static int Destroy()
    {
        if (FreeConsole())
            return 0;
        else
            return Marshal.GetLastWin32Error();
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool AllocConsole();


    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2118:ReviewSuppressUnmanagedCodeSecurityUsage"), SuppressUnmanagedCodeSecurity]
    [DllImport("kernel32.dll", SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    static extern bool FreeConsole();
}

现在,您可以调用Create()创建与应用程序关联的控制台窗口。

签出Eric Petroleje的。它显示了可以在运行时创建控制台的代码。

谢谢。成功了。现在我有另一个问题。如果生成的控制台被关闭,我的整个应用程序将关闭。有没有办法防止这种情况发生?不容易。您可以尝试使用本文中的技术禁用关闭功能: