开发者

Windows Service: Session Unlock Event with Fast User Switching and Terminal Services Stopped and Disabled

开发者 https://www.devze.com 2023-03-20 20:17 出处:网络
I am writing a C# .NET 3.5 Windows Service that needs to perform some actions whenever a user logon or unlock event occurs. I have tried registering the service by adding my event handler to Microsoft

I am writing a C# .NET 3.5 Windows Service that needs to perform some actions whenever a user logon or unlock event occurs. I have tried registering the service by adding my event handler to 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
    }
}

Also I have tried to override the OnSessionChange(SessionChangeDescription changeDescription) {...} method inherited by the ServiceBase class:

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

    base.OnSessionChange(changeDescription);
}

Many session events are handled by either of the methods described, unfortunately neither of these methods handle the event of a session unlock when fast user switching and terminal services are stopped and disabled. However the event is handled when both services are enabled and running. The work environment this will be deployed on will not have the services enabl开发者_JAVA技巧ed.

Is there another way to accomplish this within the C# .NET managed code environment? Many questions I have seen answer the question with the methods described above, they do work correctly but not when both fast user switching and terminal services is disabled.


The CanHandleSessionChangeEvent property is set to False by default.

Insert the following code when initializing the components

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


If you're having difficulty with SessionSwitchReason you can enable 'Other Logon/Logoff Events' in windows eventlog and monitor for these events yourself. It's a bit messy because you have to poll the logs in someway, but it does the trick.

See - https://stackoverflow.com/a/40675839/6715034

0

精彩评论

暂无评论...
验证码 换一张
取 消