为.NET程序提供输出类型的Windows应用程序和控制台应用程序

Dan*_*Dan 7 .net windows console-application

我有一个具有gui的C#应用​​程序,其输出类型设置为Windows应用程序.我还想从命令行调用它(通过参数),因此它也需要是一个控制台应用程序.有没有办法让我的应用程序作为Windows应用程序和控制台应用程序运行?有没有办法在运行时设置它或是编译时设置?

Han*_*ant 8

您可以附加控制台.使Program.cs中的代码如下所示:

    [STAThread]
    static void Main(string[] args) {
        if (args.Length > 0) {
            AttachConsole(-1);
            Console.WriteLine("");
            Console.WriteLine("Running in console, press ENTER to continue");
            Console.ReadLine();
        }
        else {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int pid);
Run Code Online (Sandbox Code Playgroud)