简体   繁体   中英

Is there a way to start/open the console from a WinForms/WPF application?

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?

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

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

Checkout Eric Petroelje's answer here . It shows code that can create a console at runtime.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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