C#: Is it possible to have a single application behave as Console or Windows application depending on switches?

前端 未结 7 2305
无人及你
无人及你 2020-12-09 21:25

I have a simple application that I would like to sort of automate via switches. But when I do run it via switches I don\'t really want a user interface showing. I just want

7条回答
  •  不知归路
    2020-12-09 22:13

    Whilst not exactly what you have asked, I've achieved the appearance of this behaviour in the past by using the FreeConsole pInvoke to remove the console window.

    You set the output type of the project to be a console application. You then define the extern call to FreeConsole:

    [DllImport("kernel32.dll", SetLastError=true)]
    private static extern int FreeConsole();
    

    Then, in you Main method you switch based on your conditions. If you want a UI, call FreeConsole before opening the form to clear the console window.

    if (asWinForms)
    {
        FreeConsole();       
        Application.Run(new MainForm());
    }
    else
    {
        // console logic here 
    }
    

    A console window does briefly appear at startup, but in my case it was acceptable.

    This is a bit of a hack though and has a bad smell, so I'd seriously consider whether you do want to go down this route.

提交回复
热议问题