C# Windows服务:会话解锁事件,用户快速切换,终端服务停止并禁用
我正在编写一个C#.NET 3.5 Windows服务,每当发生用户登录或解锁事件时,它都需要执行一些操作。我已尝试通过将事件处理程序添加到Microsoft.Win32.SystemEvents.SessionSwitch来注册服务:C# Windows服务:会话解锁事件,用户快速切换,终端服务停止并禁用,c#,session,windows-services,unlock,terminal-services,C#,Session,Windows Services,Unlock,Terminal Services,我正在编写一个C#.NET 3.5 Windows服务,每当发生用户登录或解锁事件时,它都需要执行一些操作。我已尝试通过将事件处理程序添加到Microsoft.Win32.SystemEvents.SessionSwitch来注册服务: using Microsoft.Win32; SystemEvents.SessionSwitch += new SessionSwitchEventHandler(SystemEvents_SessionSwitch); void SystemEvents
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(sessionchangescription changescription){…}
方法:
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托管代码环境中是否有其他方法可以实现这一点?我看到的许多问题都用上述方法回答了这个问题,它们确实可以正常工作,但当快速用户切换和终端服务都被禁用时就不行了。默认情况下,
CanHandleSessionChangeEvent
属性设置为False
在初始化组件时插入以下代码
public Service1()
{
InitializeComponent();
this.CanHandleSessionChangeEvent = true;
this.CanHandlePowerEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
this.AutoLog = true;
}
默认情况下,
CanHandleSessionChangeEvent
属性设置为False
在初始化组件时插入以下代码
public Service1()
{
InitializeComponent();
this.CanHandleSessionChangeEvent = true;
this.CanHandlePowerEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
this.AutoLog = true;
}
如果您在
会话SwitchReason
方面遇到困难,您可以在windows事件日志中启用“其他登录/注销事件”,并自己监控这些事件。这有点混乱,因为您必须以某种方式轮询日志,但它确实起到了作用
请参阅-如果您在
会话切换原因方面遇到困难,您可以在windows事件日志中启用“其他登录/注销事件”,并自己监控这些事件。这有点混乱,因为您必须以某种方式轮询日志,但它确实起到了作用
见-