how to use WtsApi32.dll in lock/Unlock session handler in windows service?

admin

Administrator
Staff member
I want to detect and close any program (for example: Notepad.exe) by using a windows service. Below code is good choose in a console application.

Code:
class Program
{
    private static SessionSwitchEventHandler sseh;
    static void Main(string[] args)
    {
        sseh = new SessionSwitchEventHandler(SystemEvents_SessionSwitch);
        SystemEvents.SessionSwitch += sseh;
        while (true) { }
    }

    static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
    {
        Console.WriteLine(e.Reason.ToString());
    }
}

But Above code is not working in a windows service windows 7. look this link :

<a href="http://social.msdn.microsoft.com/Forums/eu/netfxcompact/thread/04b16fac-043a-41c3-add9-482c912e95be" rel="nofollow">http://social.msdn.microsoft.com/Forums/eu/netfxcompact/thread/04b16fac-043a-41c3-add9-482c912e95be</a>

I have written below code in the windows service which does not run on win 7, it is working every time on windows 7 in console application.

Code:
protected override void OnStart(string[] args)
{ 
    SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
    Console.ReadLine();
    SystemEvents.SessionSwitch -= SystemEvents_SessionSwitch;
}


static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    WriteToLogFile( e.Reason.ToString());
    if (e.Reason == SessionSwitchReason.SessionLock)
    {
         WriteToLogFile("SessionLock ");
    }
    if (e.Reason == SessionSwitchReason.SessionUnlock)
    {
         WriteToLogFile("SessionUnlock ");
    }
    if (e.Reason == SessionSwitchReason.SessionLogon)
    {
         WriteToLogFile("SessionLogon ");
    }
}

I have been read this article (<a href="http://rhauert.wordpress.com/category/ucc/" rel="nofollow">http://rhauert.wordpress.com/category/ucc/</a>) but I can not use

Code:
protected override void OnStart(string[] args)
{
     WriteToText("Windows Service is started");
     SessionChangeHandler x = new SessionChangeHandler();
}