6

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.

Maxime Rouiller
  • 13,614
  • 9
  • 57
  • 107
Alan Schapira
  • 1,053
  • 4
  • 17
  • 32

1 Answers1

13

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
}
Valentin
  • 5,380
  • 2
  • 24
  • 38