首页 > 解决方案 > 服务未捕获 SessionChange 事件

问题描述

我正在编写一个应该记录一些事件的小服务。但是只有两个或工作,即使在搜索之后我也无法弄清楚为什么。

这些是我要记录的事件:


我三次检查我的服务是否可以捕获这些事件(我什至将所有CanHandle..设置为 true..

private void InitializeComponent()
{
    // 
    // Service1
    // 
    this.CanHandlePowerEvent = true;
    this.CanHandleSessionChangeEvent = true;
    this.CanPauseAndContinue = true;
    this.CanShutdown = true;
    this.ServiceName = "TimeToGoService";
}

这是我重写的 OnSessionChange()

protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
    if (changeDescription.Reason == SessionChangeReason.SessionLock)
    {
        startBreak();
    }
    else if (changeDescription.Reason == SessionChangeReason.SessionUnlock)
    {
        endBreak();
    }

    base.OnSessionChange(changeDescription);
}

startBreak()endBreak()仅使用 StreamWriter 将日志写入文件。

通过在网上搜索,我看到有些人使用隐藏表单来触发这些事件。那是问题吗?

标签: c#eventsservice

解决方案


不知道为什么,但上面的代码现在可以 100% 运行。大概错过了什么。。

编辑:无法确​​定到底出了什么问题。我可以给我的下一个在代码旁边工作的服务配置。

  • 服务用户是LocalSystem
  • CanHandleSessionChangingEvents 设置为true

而且..差不多就是这样。请注意,服务不需要与桌面交互来捕获这些事件。

此外,您可以在EventObserver中检查您的服务是否从终端获取事件,您将看到它们是失败还是成功。

祝你好运,但如果你使用上面的代码和配置,你应该可以让它工作;)


推荐阅读