WPF应用程序是否可以打印控制台输出?

10

我有一个简单的WPF应用程序。在正常使用情况下,App.xaml将启动MainWindow.xaml。但是,如果通过特殊的命令行参数调用它,我想要设置它为控制台应用程序而非窗口应用程序。

这是我的App.xaml.cs文件的大致内容:

using System;

namespace MyProject
{
    public partial class App : Application
    {
        public void App_OnStartup(object sender, StartupEventArgs e)
        {
            if (e.Args.Length == 1 && e.Args[0].Equals("/console"))
            {
                Console.WriteLine("this is a test");
                Environment.Exit(0);
            }
            else
            {
                var mainWindow = new MainWindow();
                mainWindow.Show();
            }
        }
    }
}

我希望当我在命令行中运行 MyProject.exe /console 时,它会输出字符串 "this is a test"。但现在它没有输出任何内容。我该怎么做才能让它工作?

2个回答

21

我们有专门的课程来达成这个目的:

internal static class ConsoleAllocator
{
    [DllImport(@"kernel32.dll", SetLastError = true)]
    static extern bool AllocConsole();

    [DllImport(@"kernel32.dll")]
    static extern IntPtr GetConsoleWindow();

    [DllImport(@"user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

    const int SwHide = 0;
    const int SwShow = 5;


    public static void ShowConsoleWindow()
    {
        var handle = GetConsoleWindow();

        if (handle == IntPtr.Zero)
        {
            AllocConsole();
        }
        else
        {
            ShowWindow(handle, SwShow);
        }
    }

    public static void HideConsoleWindow()
    {
        var handle = GetConsoleWindow();

        ShowWindow(handle, SwHide);
    }
}

只需调用 ConsoleAllocator.ShowConsoleWindow(),然后写入控制台。


5

如果您不想创建应用程序对象,则应创建一个包含主入口点的单独的类:

class Startup
{
    [STAThreadAttribute]
    public static int Main(string[] args)
    {
        if (args.Length == 0)
        {
            // run windowed
            App app = new App();
            app.InitializeComponent();
            app.Run();
        }
        else
        {
            // run console
            ConsoleManager.Show();
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();
        }

        return 0;
    }
}

您还需要进入应用程序设置并将“启动对象”更改为“YourProjectNamespace.Startup”,有关详细信息,请参见此文章
我调用的控制台函数来自这个问题的被接受的答案,该答案展示了如何使用标准控制台流。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接