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