我制作了一个具有 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 问题,但没有一个特别解决这个问题......那么你如何实际附加到当前控制台窗口以将此数据输出回用户(例如,给他们错误消息等) ) 但这些讨厌的问题没有出现吗?
最佳答案
我在这里找到了关于这个的讨论:
看来你运气不好,或者你不愿意诉诸丑陋的 hack。
根据上一个线程的回答:我总是选择选项 3:
“或者您可以稍微重组您的应用程序/源代码并提供两个可执行文件,一个是直接启动 GUI 的 GUI,另一个是控制台可执行文件。”
关于c# - 从 WPF 应用程序附加到现有控制台的解决方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25726220/