【发布时间】:2017-03-03 10:30:23
【问题描述】:
我有一个工作的 WPF 应用程序,我想为它配备一些控制台功能以启用批处理。
为此,我从 App.xaml 中删除了StartupUri="MainWindow.xaml",并添加了一个基于命令行参数的程序调用,调用 WPF 或控制台应用程序。
这工作正常,只是有一个问题,控制台应用程序中的第一个Console.WriteLine() 也会在命令行中输出二进制路径。
我还有什么需要改变的吗?
App.xaml.cs:
using System;
using System.Linq;
using System.Windows;
using System.Windows.Forms;
namespace AppNamespace
{
public partial class App : System.Windows.Application
{
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool FreeConsole();
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (e.Args.Contains("/c"))
{
// try to attach to an parent process console
if (!AttachConsole(-1))
{
// Alloc a new console
AllocConsole();
}
Console.WriteLine("Line 1");
Console.WriteLine("Line 2");
// get command prompt back
SendKeys.SendWait("{ENTER}");
// detach console
FreeConsole();
}
else
{
new MainWindow().ShowDialog();
}
this.Shutdown();
}
}
}
App.xaml:
<Application x:Class="AppNamespace.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
<Application.Resources>
</Application.Resources>
</Application>
命令行输出:
C:\TestProject\bin\Debug>testapp.exe /c
C:\TestProject\bin\Debug>Line 1
Line 2
C:\TestProject\bin\Debug>
我想要命令行输出:
C:\TestProject\bin\Debug>testapp.exe /c
Line 1
Line 2
C:\TestProject\bin\Debug>
【问题讨论】:
-
这是您已经从命令行或powershell(附加)启动exe的情况,还是仅在应用程序打开自己的控制台时?我从 Windows 8.1 开始观察到类似的行为,我还可以在程序仍在生成输出时与控制台交互(键入命令)。
标签: c# wpf command-line-interface