3

次のように、サービス コントローラーの 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;
        }
    }

ただし、呼び出し元のコードからコマンドを呼び出しても (コードが行にヒットし、ステップオーバーし、例外は発生しません)、何も起こりません。なんで?これはすべてローカル マシン上にあり、私には完全な管理者権限があります。

ありがとう

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 に答える