简体   繁体   English

从WPF应用程序附加到现有控制台的变通方法?

[英]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: 我已经创建了一个具有GUI的WPF应用程序,但我也希望它可以从命令行运行,所以我已经将它添加到我的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: 问题1:从命令行运行应用程序在关闭之前等待用户输入:

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 . 问题2: 这些是命令行重定向操作符 AttachConsole, for some reason, stops them from working: AttachConsole由于某种原因阻止他们工作:

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? 我已经检查了其他Stack问题,但没有特别解决这个问题...所以你怎么能真正附加到当前控制台窗口将这些数据输出回用户(例如,给他们错误信息等)但不是有这些令人讨厌的问题吗?

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: 从前一个帖子的答案:我总是选择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." “或者您可以重新构建您的应用程序/源代码并提供两个可执行文件,GUI可直接启动GUI,另一个可执行控制台。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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