我在WPF入口点
中有以下代码public partial class App : Application
{
[DllImport("kernel32.dll")]
static extern bool AttachConsole(int dwProcessId);
private const int ATTACH_PARENT_PROCESS = -1;
protected override void OnStartup(StartupEventArgs e)
{
if (e.Args.Length == 0)
{
// Launch GUI and pass arguments in case you want to use them.
base.OnStartup(e);
new MainWindow().ShowDialog();
}
else
{
//Do command line stuff
if (e.Args.Contains("-i"))
{
// redirect console output to parent process;
// must be before any calls to Console.WriteLine()
AttachConsole(ATTACH_PARENT_PROCESS);
var stopWatch = new Stopwatch();
stopWatch.Reset();
stopWatch.Start();
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
}
stopWatch.Stop();
var ts = stopWatch.Elapsed;
var elapsedTime = $"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}";
Console.WriteLine("RunTime " + elapsedTime);
}
else
{
AttachConsole(ATTACH_PARENT_PROCESS);
Console.WriteLine("Incorrect arguments");
}
}
Shutdown();
}
}
提示会立即返回,就像我的应用在后台运行一样。
我希望该应用能够阻止控制台返回,直到该过程完成。
答案 0 :(得分:1)
AttachConsole
重新使用现有的控制台使用AllocConsole()
。除非父进程正在运行,否则这将阻止控制台,并在程序完成执行后立即关闭控制台。
[DllImport("kernel32.dll")]
static extern bool AllocConsole();