SimpleGuy
SimpleGuy

Reputation: 2914

Console Application to be run as GUI as well

Before anyone marks this as Duplicate, Please read

I have a process which is Windows Application and is written in C#.

Image showing project Properties

Now I have a requirement where I want to run this from console as well. Like this.

enter image description here

Since I need to show output to console, so I changed the application type to Console Application

enter image description here

Now the problem is that, whenever user launches a process from Windows Explorer (by doubling clicking). Console window also opens in behind.

enter image description here

Is there is way to avoid this ?

What I tried after @PatrickHofman's help.

But I still have problems

Upvotes: 3

Views: 4720

Answers (1)

meh-uk
meh-uk

Reputation: 2151

OK I thought I'd have a play at this as I was curious.

  • First I updated the Main method in Program.cs to take arguments so I could specify -cli and get the application to run on the command line.
  • Second I changed the project's output type to "console application" in the project properties.
  • Third I added the following methods to Program.cs

    private static void HideConsoleWindow()
    {
        var handle = GetConsoleWindow();
    
        ShowWindow(handle, 0);
    }
    
    [DllImport("kernel32.dll")]
    static extern IntPtr GetConsoleWindow();
    
    [DllImport("user32.dll")]
    static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);
    
  • Fourth I call HideConsoleWindow as the first action in non-CLI mode.

After these steps my (basic) application looks like:

    [STAThread]
    static void Main(string[] args)
    {
        if (args.Any() && args[0] == "-cli")
        {
            Console.WriteLine("Console app");
        }
        else
        {
            HideConsoleWindow();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }

Then if I open the program on the command line with the -cli switch it runs as a command line application and prints content out to the command line and if I run it normally it loads a command line window (extremely) briefly and then loads as a normal application as you'd expect.

Upvotes: 4

Related Questions