简体   繁体   中英

Windows service inside windows form application

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM