我正在编写一个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
}
}
此外,我还尝试覆盖OnSessionChange(SessionChangeDescription changeDescription) {...}
类继承的ServiceBase
方法:
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托管代码环境中是否有另一种方法可以实现此目的?我所看到的许多问题都是用上述方法回答问题,它们确实可以正常工作,但是当快速用户切换和终端服务都被禁用时却没有。
答案 0 :(得分:0)
默认情况下,CanHandleSessionChangeEvent
属性设置为False
。
初始化组件时插入以下代码
public Service1()
{
InitializeComponent();
this.CanHandleSessionChangeEvent = true;
this.CanHandlePowerEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
this.AutoLog = true;
}
答案 1 :(得分:0)
如果您在使用Failed to convert value of type [java.lang.String] to required type [int]; nested exception is java.lang.NumberFormatException: For input string: ""
时遇到困难,可以在Windows事件日志中启用“其他登录/注销事件”,并自行监控这些事件。它有点乱,因为你必须以某种方式轮询日志,但它可以解决问题。