有没有办法从WinForms / WPF应用程序启动/打开控制台?

有没有办法从WinForms / WPF应用程序启动/打开控制台?

问题描述:

我有一个窗体窗体应用程序,我想打开一个控制台按需(当我按下一个按钮),我可以使用标准的控制台类进行交互。有没有办法做到这一点?

I have a windows forms application and i want to open a console on demand (when i press a button for example) that i can interact with using the standard Console class. Is there a way to do this?

是的,你需要一个小插件与Win32的interop 。

Yes there is you'll need a litte bit on interop with Win32 to do it.

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()创建与您的应用程序相关联的控制台窗口。

Now you can call Create() to create console window associated with your app.