簡體   English   中英

ExecuteCommand servicecontroller - 無法在服務上執行命令

[英]ExecuteCommand servicecontroller - cannot excecute command on service

我正在使用服務 controller 執行命令 function,如下所示:

            ServiceController serviceController = new ServiceController("a Service",
                Environment.MachineName);

            serviceController.ExecuteCommand(129);

並在服務 controller 中:

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

然而,盡管從調用代碼中調用了任何命令(代碼命中該行,然后跳過,沒有異常),但什么也沒有發生。 為什么? 這一切都在本地機器上,我擁有完全的管理員權限。

謝謝

您必須嘗試對已停止的服務執行命令。 添加如下內容:

    if (serviceController1.Status == ServiceControllerStatus.Stopped)
    {
        serviceController1.Start();
    }
    serviceController1.ExecuteCommand(192);

我還沒有找到它不應該工作的任何理由。 這是使用自定義命令的 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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM