【问题标题】:Is there a way to start/open the console from a WinForms/WPF application?有没有办法从 WinForms/WPF 应用程序启动/打开控制台?
【发布时间】:2009-12-23 15:26:56
【问题描述】:

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

【问题讨论】:

    标签: .net console


    【解决方案1】:

    是的,您需要一点点与 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() 来创建与您的应用关联的控制台窗口。

    【讨论】:

    • 谢谢。有效。现在我有另一个问题。如果生成的控制台关闭,我的整个应用程序就会关闭。有没有办法防止这种情况发生?
    • 不容易。您可以尝试使用本文中的技术禁用关闭功能:stackoverflow.com/questions/877839/…
    【解决方案2】:

    查看 Eric Petroelje 的 answer here。它显示了可以在运行时创建控制台的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-26
      • 2011-03-07
      • 2019-10-13
      • 2022-01-14
      • 2013-05-16
      • 2015-06-21
      相关资源
      最近更新 更多