简体   繁体   English

Windows 窗体应用程序内的 Windows 服务

[英]Windows service inside windows form application

I created a windows form application using c#.我使用 c# 创建了一个 windows 窗体应用程序。 Now I need to add a windows service along with this application.现在我需要在这个应用程序中添加一个 Windows 服务。 I added a new windows service and added installer.我添加了一个新的 Windows 服务并添加了安装程序。 I created the windows installer and installed it in a PC, but the service is not working.我创建了 Windows 安装程序并将其安装在 PC 中,但该服务不起作用。 I am new to C#.我是 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). WinForms 应用程序和 Windows 服务项目模板具有不同的引导代码(请参阅项目中的“Program.cs”文件)。

This one from Windows forms:这个来自 Windows 表单:

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

This one from Windows service:这是来自 Windows 服务的:

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 .现在,在安装服务时,您需要设置命令行参数来运行您的可执行文件: myExe service

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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