-1

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.

  • "but the service is not working" -- how can we help you without giving us more information? – rory.ap Oct 28 '15 at 12:33
  • Did you start the service? How do you know it is not working? We need way more information – Pavenhimself Oct 28 '15 at 12:34
  • Hi all, thank you for your replies, The basic problem is I am a beginner in C#. I am combining codes from internet. My requirement is, when there is no internet the data will be stored in a file. That part I am handling with windows forms. Now I need a service which check for internet connection and when internet is available it will automatically upload the file to a webservice. – Joseph Alexander Oct 29 '15 at 09:50

1 Answers1

2

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.

Dennis
  • 37,026
  • 10
  • 82
  • 150