Windows服务:使用快速用户切换和终端服务停止和禁用的会话解锁事件

3

我正在编写一个C# .NET 3.5 Windows服务,需要在用户登录或解锁事件发生时执行一些操作。我尝试通过将我的事件处理程序添加到Microsoft.Win32.SystemEvents.SessionSwitch来注册服务:

using Microsoft.Win32;

SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch);

void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (e.Reason == SessionSwitchReason.SessionLogon)
    { 
        //  Do Task
    }
    else if (e.Reason == SessionSwitchReason.SessionUnlock)
    { 
        //  Do Task
    }
}

我尝试覆盖由ServiceBase类继承的OnSessionChange(SessionChangeDescription changeDescription) {...}方法:

protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
    if (changeDescription.Reason == SessionChangeReason.SessionLogon)
    {
        //  Do Task
    }
    else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
    {
        //  Do Task
    }

    base.OnSessionChange(changeDescription);
}

很多会话事件由上述方法之一处理,不幸的是,当快速用户切换和终端服务停止和禁用时,这些方法都无法处理会话解锁事件。然而,当两个服务都启用并运行时,该事件将得到处理。在部署本工作环境时,这两个服务将被禁用。
在C#.NET托管代码环境中是否有其他方法可以实现此操作?我看到很多问题都用上述方法回答了这个问题,它们确实可以正常工作,但当快速用户切换和终端服务都禁用时就无法正常工作了。
2个回答

0

CanHandleSessionChangeEvent 属性默认设置为 False

在初始化组件时插入以下代码:

public Service1()
        {
            InitializeComponent();
            this.CanHandleSessionChangeEvent = true;
            this.CanHandlePowerEvent = true;
            this.CanPauseAndContinue = true;
            this.CanShutdown = true;
            this.CanStop = true;
            this.AutoLog = true;
        }

0
如果您在使用SessionSwitchReason时遇到困难,可以在Windows事件日志中启用“其他登录/注销事件”,并自行监视这些事件。这有点混乱,因为您必须以某种方式轮询日志,但它确实起到了作用。
请参见 - https://stackoverflow.com/a/40675839/6715034

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接