We have a service in our project that runs and we need it to get a command on log off. We could send a command via our console, but the console is a separate program which could not be running. It does not necessarily need to stop, but it does need to get a command of some sort. Is there anything with in the service which can catch a Log Off event?
[10/17/12 10:45] – The service is running as Local System.
[10/17/12 12:07] – I added the following method, but I am not getting any output when I log off or onto the computer even though I am successfully writing to the log with this message I will try again rebuilding my solution, but wanted to post this here in case I am doing something wrong.
protected override void OnSessionChange(SessionChangeDescription changeDescription)
{
WriteToDebugLog(new string[] { "OnSessionChange()",
DateTime.Now.ToLongTimeString() + " - Session change notice received: " + changeDescription.Reason.ToString() + " Session ID: " + changeDescription.SessionId.ToString(),
"Information" });
base.OnSessionChange(changeDescription);
}
Unfortunately Services cannot run per-user, they’re system wide. You may modify your service to detect when the user log-off but then it won’t be started again when the user log-in again. As alternative you may use a second service to monitor log-in activity (using OnSessionChanged as pointed out by @rene) and to start/stop the first service according.
It’s a little bit tricky and you have to install a second service, I prefer a more simple solution using scripting.
PowerShell
You can use two PowerShell scripts, this is to start the service:
This is to stop the service:
To configure this scripts to be executed take a look here. In short you have to change policy configuration in
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System!RunUserPSScriptsFirstto run your scripts when needed.“Old” shell
You’re not forced to use PowerShell, to start/stop a service can be done using shell commands:
and
See this post for how to execute a batch file (or a command) at log-off. In short you have to add an entry to
HKCU\Software\Policies\Microsoft\Windows\System\Scripts\Logofffor log-off andHKCU\Software\Policies\Microsoft\Windows\System\Scripts\Logonfor log-on (but there are many many different places where you can put your scripts for log-on).