MFedatto
MFedatto

Reputation: 134

Hybrid windows forms and console app without console window in forms mode

I want to create a complete hybrid app, working both as an Windows Forms and as a Console Application. When I execute it without arguments or not in the console I want the app to open the GUI and leave the console, just like an ordinary Windows Forms app does when called from the console, but to respond to the user and interact with him throug the console when some arguments are informed, like accepting terms ans conditions or confirming a file overwrite. Is that possible?

P.S.: I don't mind having a console output while running the GUI, but I want the console to stay hidden when running on GUI and no GUI when running as console.

NOTE

The solution sugested in how to run a winform from console application? (creating a forms project an then changing to console) doesn't attend me because it opens a console window when the app is called from the explorer.

Upvotes: 0

Views: 1596

Answers (1)

Michał Komorowski
Michał Komorowski

Reputation: 6238

The difference between WinForms and Console application lays in the fact that they are compiled in a little bit different way (see this question). The console applications have the following flag in the manifest:

.subsystem 0x0003 // WINDOWS_CUI

And WinForms applications the following:

.subsystem 0x0002 // WINDOWS_GUI

There are many questions related to this topic. For example see this one. In general, as far as I know, there is no ideal solution, but there are solutions which work to some extent. For example try this one:

  1. Create a WinForms application.
  2. Copy the code from this site.
  3. Modify Main method of WinForms application as shown below.

The modified Main method:

[STAThread]
private static void Main(string[] args)
{
   if (args.Length == 0)
   {
      Application.EnableVisualStyles();
      Application.SetCompatibleTextRenderingDefault(false);
      Application.Run(new Form1());
   }
   else
   {
      AllocateConsole();
      Console.WriteLine("I'm a console application");
      //...
      FreeConsole();
   }
}

The disadvantages of this solution are:

  1. It will not be possible to redirect output from a console application to a file.
  2. A console application will have to be closed explicitly by pressing a key if started from the command line.
  3. Read also Remarks and Important Stuff from the article I pointed above.

Upvotes: 4

Related Questions