gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:01:24 24 4
gpt4 key购买 nike

我有一个简单的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com