繁体   English   中英

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

[英]Windows service inside windows form application

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

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

暂无
暂无

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

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