Question

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.

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 :

http://social.msdn.microsoft.com/Forums/eu/netfxcompact/thread/04b16fac-043a-41c3-add9-482c912e95be

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.

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 (http://rhauert.wordpress.com/category/ucc/) but I can not use

protected override void OnStart(string[] args)
{
     WriteToText("Windows Service is started");
     SessionChangeHandler x = new SessionChangeHandler();
}
Was it helpful?

Solution

MSDN:

SystemEvents.SessionSwitch Event:

This event is only raised if the message pump is running. In a Windows service, unless a hidden form is used or the message pump has been started manually, this event will not be raised. For a code example that shows how to handle system events by using a hidden form in a Windows service, see the SystemEvents class.

The code sample is on this page, which also notes:

Services do not have message loops, unless they are allowed to interact with the desktop. If the message loop is not provided by a hidden form, as in this example, the service must be run under the local system account, and manual intervention is required to enable interaction with the desktop. That is, the administrator must manually check the Allow service to interact with desktop check box on the Log On tab of the service properties dialog box. In that case, a message loop is automatically provided. This option is available only when the service is run under the local system account. Interaction with the desktop cannot be enabled programmatically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top