简体   繁体   English

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

[英]Open a console in the wpf application

I was trying to go acording to this tutorial: https://ikriv.com/blog/?p=2470 .根据本教程,我正在尝试 go: https://ikriv.com/blog/?p=2470 So You create a WPF app and program.cs with this code:因此,您使用以下代码创建了 WPF 应用程序和 program.cs:

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

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

Then just change the Startup and Output type.然后只需更改 Startup 和 Output 类型。

However, this solution appears to break in the new .NET 5.0 while it works fine in .NET Framework.Is there a way to do this similarly easy in the new version?然而,这个解决方案似乎在新的 .NET 5.0 中出现问题,而它在 .NET 框架中运行良好。有没有办法在新版本中同样简单地做到这一点? Thank you very much.非常感谢。

@ Naman Kumar. @纳曼库马尔。

For opening Console application you could manually open Console window in WPF application( .NET 5.0).要打开控制台应用程序,您可以在 WPF 应用程序(.NET 5.0)中手动打开控制台 window。 You can add the AllocConsole and FreeConsole methods to your class and use it as shown below:您可以将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();
        }
  }

The comment from Robert Harvey solves the question.罗伯特哈维的评论解决了这个问题。 I used this tutorial ( 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 )我使用了本教程( https://ikriv.com/blog/?p=2470 )和 .NET 5.0 我遵循了这个: sdk/5.0/automatically-infer-winexe-output-type )

You can not accept a comment, so I hope it does not matter if I write the summary like this.你不能接受评论,所以我希望我这样写总结也没关系。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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