I have an working WPF application which I wanted to eqip with some console functionalities to enable batch processing.
To do so, I deleted StartupUri="MainWindow.xaml"
from my App.xaml, and added instead a programatic call based on command line arguments, calling either the WPF or the console application.
This is working fine, just with one problem, the first Console.WriteLine()
in the console application also puts out the binary path in command line.
Is there anything I also have to change?
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>
Command line output:
C:\TestProject\bin\Debug>testapp.exe /c
C:\TestProject\bin\Debug>Line 1
Line 2
C:\TestProject\bin\Debug>
Command line output wanted from me:
C:\TestProject\bin\Debug>testapp.exe /c
Line 1
Line 2
C:\TestProject\bin\Debug>