バッチ処理を有効にするためにいくつかのコンソール機能でeqipしたいWPFアプリケーションがあります。 これを行うには、私は自分のApp.xamlからStartupUri="MainWindow.xaml"
を削除し、代わりにWPFまたはコンソールアプリケーションのいずれかを呼び出すコマンドライン引数に基づいたプログラム呼び出しを追加しました。 これはうまくいきました。ただ1つの問題で、コンソールアプリケーションの最初のConsole.WriteLine()
もコマンドラインにバイナリパスを出力します。C#:WPFと同じアプリケーションのコマンドライン
変更する必要があるものはありますか?
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(attach)からexeを起動した場合、またはアプリケーションが独自のコンソールを開いた直後の場合です。私は、Windows 8.1以降でも、プログラムが出力を生成している間にコンソール(タイプコマンド)とやりとりすることができる同様の動作を観察しました。 – dlatikay