How do I create a C# app that decides itself whether to show as a console or windowed app?

前端 未结 11 819
广开言路
广开言路 2020-11-28 21:10

Is there a way to launch a C# application with the following features?

  1. It determines by command-line parameters whether it is a windowed or console app
11条回答
  •  余生分开走
    2020-11-28 21:22

    No 1 is easy.

    No 2 can't be done, I don't think.

    The docs say:

    Calls to methods such as Write and WriteLine have no effect in Windows applications.

    The System.Console class is initialized differently in console and GUI applications. You can verify this by looking at the Console class in the debugger in each application type. Not sure if there's any way to re-initialize it.

    Demo: Create a new Windows Forms app, then replace the Main method with this:

        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
            }
            else
            {
                Console.WriteLine("Console!\r\n");
            }
        }
    

    The idea is that any command line parameters will print to the console and exit. When you run it with no arguments, you get the window. But when you run it with a command line argument, nothing happens.

    Then select the project properties, change the project type to "Console Application", and recompile. Now when you run it with an argument, you get "Console!" like you want. And when you run it (from the command line) with no arguments, you get the window. But the command prompt won't return until you exit the program. And if you run the program from Explorer, a command window will open and then you get a window.

提交回复
热议问题