WPF / Console Hybrid Application

后端 未结 4 1909
长发绾君心
长发绾君心 2021-02-13 01:27

I writing an application what can either be run on the command line, or with a WPF UI.

[STAThread]
static void Main(string[] args)
{
    // Does magic parse args         


        
4条回答
  •  忘掉有多难
    2021-02-13 02:26

    Create a WPF app and add the following code to your App class:

    public partial class App
    {
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args.Length > 0)
            {                
                List lowercaseArgs = e.Args.ToList().ConvertAll(x => x.ToLower());
                if (AttachConsole(ATTACH_PARENT_PROCESS))
                {
                    // your console app code                
    
                    Console.Write("\rPress any key to continue...");
                    Console.ReadKey();
                    FreeConsole();
                }
                Shutdown();
            }
            else
            {
                base.OnStartup(e);
            }
        }
    
        private const int ATTACH_PARENT_PROCESS = -1;
    
        [DllImport("kernel32", SetLastError = true)]
        private static extern bool AttachConsole(int dwProcessId);
    
        [DllImport("kernel32.dll")]
        private static extern bool FreeConsole();
    }
    

提交回复
热议问题