Windows服务:OnPowerEvent不会触发

Moo*_*oon 2 .net c# service windows-services

我想创建一个Windows服务来跟踪是否插入了A/C电源适配器.为此,我正在尝试构建如下的Windows服务:

using System;
using System.ServiceProcess;

namespace PowerAlert {
    partial class PowerAlert : ServiceBase {
        public PowerAlert() {
            InitializeComponent();
        }

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

        protected override void OnStop() {
            base.OnStop();
        }

        protected new virtual void OnPowerEvent(PowerBroadcastStatus powerStatus) {
            Console.Beep();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

安装服务并从services.msc启动它后,当我拔下我的适配器并将其重新插入时,我听不到哔声.

我确信我没有正确地做某事.你能帮我识别那些/那些东西吗?

编辑1

从下面可以看出,CanHandlePowerEvent设置为true.

namespace PowerAlert {
    partial class PowerAlert {
        /// <summary> 
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing) {
            if (disposing && (components != null)) {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Component Designer generated code

        /// <summary> 
        /// Required method for Designer support - do not modify 
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
            // 
            // PowerAlert
            // 
            this.CanHandlePowerEvent = true;
            this.ServiceName = "PowerAlert";
        }

        #endregion
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经覆盖了OnPowerEvent,如下所示:

using System;
using System.ServiceProcess;

namespace PowerAlert{
    partial class PowerAlert: ServiceBase {
        public PowerAlert() {
            InitializeComponent();
        }

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

        protected override void OnStop() {
            base.OnStop();
        }

        protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus) {
            Console.Beep();

            return base.OnPowerEvent(powerStatus);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我仍然听不到任何哔哔声.

Hen*_*sel 7

除了覆盖方法的错误语法之外,看起来您没有设置CanHandlePowerEvent属性.

当计算机电源状态发生更改时,服务控制管理器(SCM)将使用CanHandlePowerEvent的值验证服务是否接受电源事件命令.

如果CanHandlePowerEvent为true,则将命令传递给服务,并在定义时调用OnPowerEvent方法.如果未在派生类中实现OnPowerEvent,则SCM通过空基类ServiceBase.OnPowerEvent method.ServiceBase.OnPowerEvent方法处理power事件.

请关于该方法的一件事:

64位版本的Windows Vista和Windows XP不支持Beep方法.