简体   繁体   中英

Workarounds to attaching to existing console from WPF application?

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?

I found a discussion about this here:

The problem of attachconsole

Seems you are out of luck or if you are not willing to resort to an ugly hack.

From the previous thread's answer: I always have gone with option 3:

"Or you can restructure your application/source a bit and provide two executables, GUI one that starts GUI directly, another that is console executable."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM