Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide the console window from a console application [duplicate]

Tags:

c#

I have an application that was using the console, but I changed all the code to write to a file instead of the console. I would now like the console to stop appearing when I run the application. How do I do this? I do not know what is opening the console in the first place, even though nothing is being written to it in the code.

I have looked in the applications references and cannot find System.Console being referenced. I though disabling that would fix it or point me in the right direction with errors. I am not sure where else to look.

All the other things I found online talk about making the console hidden. I would like it to not appear in the first place.

like image 436
Alan Schapira Avatar asked Dec 25 '22 11:12

Alan Schapira


1 Answers

Go to the Application Properties and change Output Type from Console Application to Windows Application.

Or you can do it using a code below

using System.Runtime.InteropServices;
[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

And in main

const int SW_HIDE = 0;
const int SW_SHOW = 5;
var handle = GetConsoleWindow();

ShowWindow(handle, SW_HIDE); // To hide
ShowWindow(handle, SW_SHOW); // To show

Also, you can run you application as a service. In order to do this you should create a service - File->New Project->Visual C#->Windows->Windows Service. Then create a public method StartWork() and add all you logic there. And call this method in OnStart().

 protected override void OnStart(string[] args)
    {
        try
        {
            this.StartJobs();
        }
        catch (Exception ex)
        {
            // catching exception
        }
    }

    public void StartWork()
    {
       // all the logic here
    }

In main you should create this service and use System.ServiceProcess.ServiceBase.Run() to run it as service or call StartWork() to run it as console application.

static void Main(string[] args)
{
    TestService = new  TestService ();

    #if DEBUG
        TestService.StartWork()();
    #else
        System.ServiceProcess.ServiceBase.Run(TestService ); 
    #endif
}
like image 65
Valentin Avatar answered Mar 23 '23 07:03

Valentin