在 wpf 应用程序中打开控制台

Open a console in the wpf application

我试图按照本教程进行操作:https://ikriv.com/blog/?p=2470。因此,您使用以下代码创建了一个 WPF 应用程序和 program.cs:

class Program
{
    [STAThread]
    public static void Main(string[] args)
    {
        var app = new App();

        app.InitializeComponent();
        app.Run();
    }
}

然后只需更改启动和输出类型即可。

但是,此解决方案似乎在新的 .NET 5.0 中出现问题,但在 .NET 中运行良好 Framework.Is 有没有一种方法可以在新版本中同样轻松地完成此操作?非常感谢。

@纳曼·库马尔。

要打开控制台应用程序,您可以在 WPF 应用程序 (.NET 5.0) 中手动打开控制台 window。您可以将 AllocConsoleFreeConsole 方法添加到您的 class 并使用它,如下所示:

public partial class MainWindow : Window
    {
        [DllImport("Kernel32")]
        public static extern void AllocConsole();

        [DllImport("Kernel32", SetLastError = true)]
        public static extern void FreeConsole();

        public MainWindow()
        {
            InitializeComponent();
            OutputTextBox.Focus();
            AllocConsole();
        }
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var line = OutputTextBox.Text;
            Console.Out.WriteLine(line);
        }
private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            FreeConsole();
        }
  }

Robert Harvey 的评论解决了这个问题。我使用了这个教程(https://ikriv.com/blog/?p=2470) and for a .NET 5.0 I followed this:(https://docs.microsoft.com/en-us/dotnet/core/compatibility/sdk/5.0/automatically-infer-winexe-output-type)

不能接受评论,希望我这样写总结不要紧