Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wpf and commandline app in the same executable

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)?

like image 324
Wilbert Avatar asked Aug 25 '15 12:08

Wilbert


1 Answers

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();
}
like image 167
GrahamS Avatar answered Sep 16 '22 15:09

GrahamS