我正在使用服务控制器executecommand函数,如下所示:
ServiceController serviceController = new ServiceController("a Service",
Environment.MachineName);
serviceController.ExecuteCommand(129);
在服务控制器中:
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
// Depending on the integer passed in, the appropriate method is called.
switch (command)
{
case 129:
RestartSpooler();
break;
case 131:
InstallPrinter();
break;
case 132:
DeletePrinter();
break;
}
}
然而,尽管调用了调用代码中的任何命令(代码命中行,然后跳过,没有例外),但没有任何反应。为什么?这都在本地机器上,我有完全的管理权限。
由于
答案 0 :(得分:1)
您必须尝试对已停止的服务执行命令。添加如下内容:
if (serviceController1.Status == ServiceControllerStatus.Stopped)
{
serviceController1.Start();
}
serviceController1.ExecuteCommand(192);
答案 1 :(得分:0)
我没有找到任何理由不应该起作用。 以下是使用自定义命令
的Windows服务的工作示例public partial class TestService : ServiceBase
{
public TestService()
{
InitializeComponent();
}
protected override void OnStart(string[] args) { }
protected override void OnStop() { }
protected override void OnCustomCommand(int command)
{
base.OnCustomCommand(command);
switch (command)
{
case 129:
//
break;
case 131:
//
break;
case 132:
//
break;
}
}
}
服务安装程序
[RunInstaller(true)]
public partial class Installer : System.Configuration.Install.Installer
{
public Installer()
{
InitializeComponent();
_processInstaller = new ServiceProcessInstaller();
_processInstaller.Account = ServiceAccount.LocalSystem;
_serviceInstaller = new ServiceInstaller();
_serviceInstaller.StartType = ServiceStartMode.Manual;
_serviceInstaller.ServiceName = "TestService";
Installers.Add(_serviceInstaller);
Installers.Add(_processInstaller);
}
private readonly ServiceInstaller _serviceInstaller;
private readonly ServiceProcessInstaller _processInstaller;
}
服务使用
var serviceController = new ServiceController("TestService", Environment.MachineName);
serviceController.ExecuteCommand(129);