c# - 从 WPF 应用程序附加到现有控制台的解决方法?

标签 c# .net wpf command-line console

我制作了一个具有 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.
}

这种方法有两个问题:

问题 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.

问题 2:These are command line redirection operators .由于某种原因,AttachConsole 会阻止它们工作:

C:\Code>GenerateReport.exe -output Example.html > Log.txt <-- Causes no output in Log.txt (just an empty file)!

我已经检查了其他 Stack 问题,但没有一个特别解决这个问题......那么你如何实际附加到当前控制台窗口以将此数据输出回用户(例如,给他们错误消息等) ) 但这些讨厌的问题没有出现吗?

最佳答案

我在这里找到了关于这个的讨论:

The problem of attachconsole

看来你运气不好,或者你不愿意诉诸丑陋的 hack。

根据上一个线程的回答:我总是选择选项 3:

“或者您可以稍微重组您的应用程序/源代码并提供两个可执行文件,一个是直接启动 GUI 的 GUI,另一个是控制台可执行文件。”

关于c# - 从 WPF 应用程序附加到现有控制台的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726220/

相关文章:

c# - 使用 ServiceController 类与 Windows 服务通信

c# - 为什么 selectedindexchanged 不触发?

c# - Function<> 可以递归调用自身吗?

c# - 如何恢复/中断 BackgroundWorker 线程

c# - DataGridTextColumn 只读行为,如 TextBox

WPF:如何让 ListViewItems 适合窗口宽度并使用 TextEllipsis

wpf - RichTextBox 中的 KeyBinding 手势 "Ctrl+1"不起作用

c# - IEnumerable 与 IQueryable

c# - SizeChanged 事件,但仅在全部更改完成后发生

c# - DllImport 期间出现 FatalExecutionEngineError