3

我正在使用服务控制器执行命令功能,如下所示:

            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;
        }
    }

然而,尽管从调用代码中调用了任何命令(代码命中该行,然后跳过,没有异常),但什么也没有发生。为什么?这一切都在本地机器上,我拥有完全的管理员权限。

谢谢

4

2 回答 2

1

您必须尝试对已停止的服务执行命令。添加如下内容:

    if (serviceController1.Status == ServiceControllerStatus.Stopped)
    {
        serviceController1.Start();
    }
    serviceController1.ExecuteCommand(192);
于 2011-10-28T06:12:30.287 回答
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);
于 2011-04-27T14:25:36.093 回答