简体   繁体   中英

Implement command line run in a WPF project

I want to implement the command line run in a WPF project. The entry points has been changed in the App.cs. But the console will only blink and then disappear. How to fix that? Thanks

public class App : System.Windows.Application
{
    [STAThread]
    static void Main(string[] args)
    {
        if (args.Length > 0)
        {// Commandline run mode
            // Command line given, console from console
            Console.WriteLine("In cmd line mode");
            AllocConsole();
            CmdLineRun.ParseArgs(args);
            CmdLineRun.CmdRun();
        }
        else
        {// GUI mode
            GUIMain();
        }
    }

    static void GUIMain()
    {
        App app = new App();
        app.StartupUri = new System.Uri("MainWindow.xaml", System.UriKind.Relative);
        app.Run();
    }

    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AllocConsole();
}

When you create a new console window with AllocConsole it only sticks around while your process is still active. To prevent this, you have a couple of options:

  1. Don't actually terminate your process until the user provides some input. This is your cliche "press any key to continue" option, which you'd do after your CmdRun method returned. The console window will still disappear but only when you tell it.

  2. Use a pre-existing console. If you always run your application from a command line, you don't need to make a new console window. Instead, use the AttachConsole method to attach your stdin/stdout to the one that already exists.

The best bet is usually to try to AttachConsole(-1) (-1 means ATTACH_PARENT_PROCESS ) first. If that returns 0, then your parent process did not have a console, or else you were unable to attach to it. Then you can fall back on AllocConsole , and deal with keeping it around after shutting down.

This is not specific to WPF, it's a problem any time you try to mix console and GUI code in the same application. If your app was compiled for the CUI subsystem, by specifying "console application", Windows would handle this for you, but you wouldn't get a message queue by default and windowed UI would fail. If your app was compiled for the GUI subsystem, by specifying "windows application", you get a message queue but not console handling. Letting Windows handle the GUI part and managing the console by hand is by far the easier of the two options.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM