Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 it to run, do it's job, print stuff out in the console, and exit. On the other hand if I don't run it with any switches I want the user interface to pop up. And in this case I don't really want a console window hanging around in the background.

Is there any way I can do this, or do I have to create two separate projects, one Console Application and one Windows Application?

like image 876
Svish Avatar asked Nov 23 '09 23:11

Svish


2 Answers

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.

like image 146
adrianbanks Avatar answered Oct 16 '22 01:10

adrianbanks


From 'The Old New Thing'

How do I write a program that can be run either as a console or a GUI application?

You can't.

(I'll let you click on the article for the details of how to fake it)

like image 33
Aaron Avatar answered Oct 16 '22 03:10

Aaron