I've made a WPF application that has a GUI but I also want it to optionally run from command line, so I have added this to my App.xaml.cs:
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int pid);
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (e.Args.Count() > 0)
{
CreateReport(e.Args);
Environment.Exit(0);
}
}
void CreateReport(string[] arguments)
{
AttachConsole(-1);
// Parse arguments, generate report, etc.
}
There are two problems with this approach:
Problem 1: Running the application from command-line waits for user input before it closes:
C:\Code>GenerateReport.exe -output Example.html
Started report generation.
Report has been generated.
<-- Console waits until user input here, even though the application has finished doing its business.
Problem 2: These are command line redirection operators. AttachConsole, for some reason, stops them from working:
C:\Code>GenerateReport.exe -output Example.html > Log.txt <-- Causes no output in Log.txt (just an empty file)!
I've checked other Stack questions but none address this issue in particular...so how can you actually attach to the current console Window to output this data back to the user (for example, give them error messages, etc.) but not have these nasty problems come out of it?