I have the following code in WPF entry point
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();
}
}
The prompt returns immediately as though my app runs in the background.
I would expect the app to block the console from being returned until the process is completed.
The AttachConsole
re-uses the existing console use AllocConsole()
instead. This will block the console unless the parent process is running and will close the console as soon as the program finishes execution.
[DllImport("kernel32.dll")]
static extern bool AllocConsole();
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.