如何使我的 Windows 服务以下列方式工作...
1.) 安装后自动启动
2.) 自动启动,即使我们只是双击可执行文件
换句话说,我不想使用“NET START”、“SC”命令,也不想通过服务控制台启动它。我只想让我的服务自动安装并自动启动......加上双击可执行文件时自动启动。
谢谢。
如何使我的 Windows 服务以下列方式工作...
1.) 安装后自动启动
2.) 自动启动,即使我们只是双击可执行文件
换句话说,我不想使用“NET START”、“SC”命令,也不想通过服务控制台启动它。我只想让我的服务自动安装并自动启动......加上双击可执行文件时自动启动。
谢谢。
您可以在这样的commited
事件中使用它:
[RunInstaller(true)]
public class ServiceInstaller : Installer
{
string serviceName = "MyServiceName";
public ServiceInstaller()
{
var processInstaller = new ServiceProcessInstaller();
var serviceInstaller = new ServiceInstaller();
processInstaller.Account = ...;
processInstaller.Username = ...;
processInstaller.Password = ...;
serviceInstaller.DisplayName = serviceName;
serviceInstaller.StartType = ServiceStartMode.Automatic;
serviceInstaller.ServiceName = serviceName;
this.Installers.Add(processInstaller);
this.Installers.Add(serviceInstaller);
this.Committed += new InstallEventHandler(ServiceInstaller_Committed);
}
void ServiceInstaller_Committed(object sender, InstallEventArgs e)
{
// Auto Start the Service Once Installation is Finished.
var controller = new ServiceController(serviceName);
controller.Start();
}
}
查看 Topshelf 项目 ( http://topshelf-project.com ) 并消除在 .NET 中编写 Windows 服务的所有复杂性。它处理所有自注册并消除应用程序对服务代码的所有依赖关系。
它也是开源的并托管在 GitHub 上,因此可以轻松适应任何应用程序。
(完全披露,我是该项目的作者之一)
您可以添加调用安装程序 ( use ManagedInstallerClass.InstallHelper()
) 的命令行参数和启动服务的代码...
public class DataImportService : ServiceBase
{
// ----------- Other code -----------
static void Main(string[] args)
{
if (args.Length == 0)
{
InstallService(false, argValue); break;
StartService();
}
else
{
string arg0 = args[0],
switchVal = arg0.ToUpper(),
argValue = arg0.Contains(":") ?
arg0.Substring(arg0.IndexOf(":")) : null;
switch (switchVal.Substring(0, 1))
{
//Install Service and run
case ("I"): case ("-I"): case ("/I"):
InstallService(true, argValue); break;
// Start Service
case ("S"): case ("-S"): case ("/S"):
StartService();
default: break;
// Install & Start Service
case ("IS"): case ("-IS"): case ("/IS"):
InstallService(false, argValue); break;
StartService();
// Uninstall Service
case ("U"): case ("-U"): case ("/U"):
InstallService(false, argValue); break;
default: break;
}
}
private static void InstallService(bool install, string argFileSpec)
{
string fileSpec = Assembly.GetExecutingAssembly().Location;
if (!String.IsNullOrEmpty(argFileSpec)) fileSpec = argFileSpec;
// ------------------------------------------------------------
string[] installerParams =
install? new string[] { fileSpec } :
new string[] { "/u", fileSpec };
ManagedInstallerClass.InstallHelper(installerParams);
}
private void StartService()
{
var ctlr = new ServiceController();
ctlr.ServiceName = "MyService"; // hard code the service name
// Start the service
ctlr.Start();
}
}
我在此处-install
的帖子展示了如何使用选项从命令行安装您的 Windows 服务。您可以将此逻辑扩展为具有一个-start
选项,然后在桌面上创建一个包含该选项的快捷方式。