[英]Windows Service: Session Unlock Event with Fast User Switching and Terminal Services Stopped and Disabled
我正在編寫一個 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
class 繼承的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);
}
許多 session 事件由上述任何一種方法處理,不幸的是,當快速用戶切換和終端服務停止和禁用時,這些方法都不能處理 session 解鎖事件。 但是,當兩個服務都啟用並運行時,會處理該事件。 將在其上部署的工作環境不會啟用服務。
在 C# .NET 托管代碼環境中是否有另一種方法可以實現此目的? 我看到的許多問題都使用上述方法回答了這個問題,它們確實可以正常工作,但在禁用快速用戶切換和終端服務時不能正常工作。
如果您在使用SessionSwitchReason
時遇到困難,您可以在 windows 事件日志中啟用“其他登錄/注銷事件”並自己監控這些事件。 這有點混亂,因為您必須以某種方式輪詢日志,但它確實有效。
CanHandleSessionChangeEvent
屬性默認設置為False
。
初始化組件時插入以下代碼
public Service1()
{
InitializeComponent();
this.CanHandleSessionChangeEvent = true;
this.CanHandlePowerEvent = true;
this.CanPauseAndContinue = true;
this.CanShutdown = true;
this.CanStop = true;
this.AutoLog = true;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.