Windows service inside windows form application

2.9k Views Asked by At

I created a windows form application using c#. Now I need to add a windows service along with this application. I added a new windows service and added installer. I created the windows installer and installed it in a PC, but the service is not working. I am new to C#. Please help me to add this service to the installer.

1

There are 1 best solutions below

1
Dennis On

WinForms application and Windows service project templates have different bootstrap code (see "Program.cs" file in your project).

This one from Windows forms:

Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());

This one from Windows service:

ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
    new Service1()
};
ServiceBase.Run(ServicesToRun);

If you want to combine these types of application in a single executable, you need to modify bootstrap code a little:

// we need command line arguments in Main method
[STAThread]
static void Main(string[] args)
{
    if (args.Length > 0 && args[0] == "service")
    {
        // runs service;
        // generated bootstrap code was simplified a little
        ServiceBase.Run(new[]
        {
            new Service1()
        });
    }
    else
    {
        // runs GUI application
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}

Now, when installing service, you need to setup command line arguments to run your executable: myExe service.