1

I have an C# application runing at the back ground. Now i want to stop this application when the system is locked. how can i do that. Any help regarding this is really appreciated.

Thanks Hougen for the solution. could you please suggest me should we include any Dlls to handle "Microsoft.Win32.SystemEvents.SessionSwitch" this event? And in which layer this code should reside. I guess it is in Business layer. Any sugeestion regading this?

dsolimano
  • 8,870
  • 3
  • 48
  • 63
  • 3
    What does your question have to do with the keyboard? – Joey Sep 21 '09 at 10:42
  • Are you thinking about catching Win+L keyboard combination? I don't think that would solve your problem since the computer can still get locked using other methods... – David Božjak Sep 21 '09 at 10:46
  • Do you mean locked, as in Win+L, or locked as in frozen, crashed? – Dale Sep 21 '09 at 10:51
  • Well, if the system is crashed I think you don't need to worry about running applications anymore :-) – Joey Sep 21 '09 at 10:52
  • 2
    duplicate? http://stackoverflow.com/questions/44980/how-can-i-programmatically-determine-if-my-workstation-is-locked – Michael Niemand Sep 21 '09 at 10:55
  • @Johannes Rössel - I think he means when the account is locked and you are required to type a password in to unlock it. – ICR Sep 21 '09 at 12:01
  • It's usually best to put the actual problem you are trying to solve in the title, not the problems you are having with a proposed problem. You can, obviously, then include your proposed solution and it's problem in the question. Currently anyone who knows how to identify when the system is locked but doesn't know how to hook keys will overlook your question when they actually have a valid alternative solution. – ICR Sep 21 '09 at 12:04

1 Answers1

9

Easy. Make an event handler for the

Microsoft.Win32.SystemEvents.SessionSwitch

event. In it, check the SessionSwitchEventArgs.Reason property for the value SessionSwitchReason.SessionLock.

Shyam: sorry for not coming back to you right away. You shouldn't have to include any special DLLs. The SystemEvents class is in the System assembly. Whether this handler belongs in the business layer - I guess it belongs in whatever project contains your service class - the one that inherits from WindowsService.

public MyService()
{
    InitializeComponent();
    SystemEvents.SessionSwitch += SystemEvents_SessionSwitch;
}

void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e)
{
    if (_isRunning)
    {
        // Pause
    }
}
Tor Haugen
  • 19,509
  • 9
  • 45
  • 63