Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a Console via Program logic

Tags:

c#

service

I have a windows service. If I start it from the debugger I want to run with console output (since you can not run a service).

Usually a Windows Service is set to WindowApplication as project type and has no "window" entry point. Thus it removes the good old console.

If you want a console window you need to change the project type to ConsoleAppication. I would like to do this within the program itself instead changing the Project settings.

Is it possible?

like image 694
Jaster Avatar asked Feb 21 '26 11:02

Jaster


1 Answers

Actually you can use a simple check when the program starts to see if it is running as a service or not and then use the AllocConsole command to start the console. Here is the sample code.

namespace TestService 
{
   static class Program
   {
        [DllImport("kernel32.dll")]
        static extern bool AllocConsole();

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        static void Main()
        {
            if (!Environment.UserInteractive)                                
            {
                ServiceBase[] ServicesToRun;
                ServicesToRun = new ServiceBase[] 
                { 
                    new Service1() 
                };
                ServiceBase.Run(ServicesToRun);
            }
            else 
            {
                AllocConsole();
                //Start Code that interfaces with console.
            }           
         }        
     }
 }
like image 126
ExCodeCowboy Avatar answered Feb 22 '26 23:02

ExCodeCowboy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!