如何使我的Windows服务按照以下方式工作...
1.) 安装后自动启动
2.) 即使我们只是双击可执行文件,也可以自动启动
换句话说,我不想使用“NET START”、“SC”命令,并且不想通过服务控制台启动它。我只希望我的服务能够自动安装和自动启动...并在双击可执行文件时自动启动。
谢谢。
如何使我的Windows服务按照以下方式工作...
1.) 安装后自动启动
2.) 即使我们只是双击可执行文件,也可以自动启动
换句话说,我不想使用“NET START”、“SC”命令,并且不想通过服务控制台启动它。我只希望我的服务能够自动安装和自动启动...并在双击可执行文件时自动启动。
谢谢。
请查看ServiceController类。
您可以在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上,这使得它易于适应任何应用程序。
(完全披露,我是该项目的作者之一)
您可以添加调用安装程序的命令行参数(使用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();
}
}
ServiceController()
类启动和停止服务。您需要决定如何编写此主例程才能完成它...这取决于您... - Charles Bretana我的这篇文章展示了如何使用-install
选项从命令行安装Windows服务。你可以扩展这个逻辑,添加一个-start
选项,并创建一个包含该选项的桌面快捷方式。