windows服务命令 转载

本文介绍如何在Windows服务中实现自定义命令处理。通过定义枚举类型来指定不同的自定义命令,并在服务中实现OnCustomCommand方法以响应这些命令。此外,还展示了如何从客户端应用程序调用这些自定义命令。

OnCustomCommand executes when the Service Control Manager (SCM) passes a custom command to the service. Specifies actions to take when a command with the specified parameter value occurs.

The only values for a custom command that you can define in your application or use in OnCustomCommand are those between 128 and 256.
Integers below 128 correspond to system-reserved values.

Create One Windows Service & Implement Below Code in Service :

namespace MyWindowsService
{
    public partial class Service1 : ServiceBase
    {
        public enum SimpleServiceCustomCommands { Command1 = 128, Command2 =129, Command3 = 130};
 
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
        }

        protected override void OnStop()
        {
        }

        protected override void OnCustomCommand(int command)
        {
            base.OnCustomCommand(command);

            switch(command)
            {
                case(int)SimpleServiceCustomCommands.Command1:
                //Command1 Implementation
                break;

                case(int)SimpleServiceCustomCommands.Command2:
                //Command2 Implementation
                 break;

                case(int)SimpleServiceCustomCommands.Command3:
                //Command3 Implementation
                    break;
                default:
                    break;
 
           }       
        }
    } }

Call Windows Service CustomCommands From User Application :

  • Create Service Controller Object 

    ServiceController Controller = new ServiceController("MyWindowsService");
     
  • Start the Windows Service

    Controller.Refresh(); //Gets the current status of service
        if (Controller.Status == ServiceControllerStatus.Stopped)
         {
     Controller.Start();
         }

     
  • Call CustomCommands Using Controller Object
     

    if (Controller.Status == ServiceControllerStatus.Running)
      {
          Controller.ExecuteCommand(128); 
         }
     

转载于:https://www.cnblogs.com/baozhu/p/5171207.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值