I would like to have a single executable file that I can use to either open a graphical app (the default use case, when clicking on the .exe), or that I can use to run command line tasks.
Is this possible?
If so, how would I have to modify my app.xaml/app.xaml.cs so it only opens the graphical view on specific conditions (e.g. no commandline parameters)?
As @BrunoKlein suggested, I remove the StartupUri
property from App.xml
and then override the OnStartup
method. However I use AttachConsole
instead, as I found that AllocConsole
caused an extra console window to appear when run from command prompt.
It is also important to call FreeConsole
and Shutdown
to exit cleanly.
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
if (e.Args.Length == 0)
{
// No command line arguments, so run as normal Windows application.
var mainWindow = new MainWindow();
mainWindow.ShowDialog();
}
else
{
// Command-line arguments were supplied, so run in console mode.
try
{
const int ATTACH_PARENT_PROCESS = -1;
if (AttachConsole(ATTACH_PARENT_PROCESS))
{
CommandLineVersionOfApp.ConsoleMain(e.Args);
}
}
finally
{
FreeConsole();
Shutdown();
}
}
}
[DllImport("kernel32")]
private static extern bool AttachConsole(int dwProcessId);
[DllImport("kernel32")]
private static extern bool FreeConsole();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With