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

时间:2015-10-28 12:32:45

标签: c# windows windows-services windows-desktop-gadgets

我使用c#创建了一个Windows窗体应用程序。现在我需要添加一个Windows服务以及此应用程序。我添加了一个新的Windows服务并添加了安装程序。我创建了Windows安装程序并将其安装在PC中,但该服务无法正常工作。我是C#的新手。请帮我将此服务添加到安装程序。

1 个答案:

答案 0 :(得分:1)

WinForms应用程序和Windows服务项目模板具有不同的引导代码(请参阅项目中的“Program.cs”文件)。

来自Windows的这个表格:

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

来自Windows服务的这个:

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

如果要在单个可执行文件中组合这些类型的应用程序,则需要稍微修改引导代码:

// 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());
    }
}

现在,在安装服务时,您需要设置命令行参数来运行可执行文件:myExe service