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

标签 c# wpf console

我有一个简单的 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”。但现在它不打印任何东西。我怎样才能让它发挥作用?

最佳答案

为此我们有专门的类(class):

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() 然后写入控制台

关于c# - 是否可以让 WPF 应用程序打印控制台输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31978826/

相关文章:

c# - WrapGrid 和大量图像

c# - 在 ListBox 中显示自定义对象列表,为每个对象使用自定义用户控件

c# - 如何使用 CanContentScroll tr​​ue 获取 ItemsControl 的开发独立像素中的 ScrollViewer 的 VerticalOffset

ios - Swift - 将控制台日志重定向到文档文件夹

c# - 如何使用 C# 在 ASP.Net 中设置 DropDownList 项目的值

c# - 获取Azure Function App v2的根目录

javascript - 为什么字符串中的反斜杠(\)在控制台中给出错误

c++ - 在 Visual C++ 控制台应用程序中显示图像?

c# - Linq-to-Entities/Linq-to-SQL,哪种数据轮询方式更高效?

wpf - 使用 Microsoft.Build 程序集构建 WPF 应用程序