i have a windows service that get user details and save the result into log text file. and, my problem is when i log off my system and login again ie without restarting the machine.., i also would like to save the time that i login my system into that log file.. How can write a login event in window service.. pls help with comments
I have used the below code, but nothing was written to the log text file on log on. ie LogOn no-1 or LogOn no-2... Is there any mistake or logon didnt get enough time to execute the process..
Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e)
{
StreamWriter str = new StreamWriter("D:\\Log.txt", true);
str.WriteLine("LogOn no-1: " + DateTime.Now.ToString());
str.Close();
if (e.Reason == SessionSwitchReason.SessionLogon)
{
StreamWriter str1 = new StreamWriter("D:\\Log.txt", true);
str1.WriteLine("LogOn no-2: " + DateTime.Now.ToString());
str1.Close();
}
}
http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicebase.onsessionchange.aspx
This may be your best bet, as Vista and Win7 handle the user sessions much like a terminal server would. This should let you handle session changes and it gives a structure with the relevant information, if you want session ID or reason for session change (logon / logoff / lock etc)
These events are not raised unless a message loop is provided; manually by adding a hidden form (or may be allowing the Service to interact with the desktop - not sure never tired, may be not recommended).
I'd a similar issue with one of the services not receiving TimeZone changes, so had to add a hidden form to the service.
Here is one of the examples as to how to solve the issue.
And below is what I did to solve my issue:
Added the TimeZoneForm to the service.sln;
And in the Service's OnStart add this code :
new System.Threading.Thread(RunMessagePump).Start();
And add this method to the service file:
Take a look into the
SystemEvents
class, here's the MSDN link.Relevant in your case are the exposed events
SessionEnded
,SessionEnding
andSessionSwitch
and potentiallyPowerModeChanged
.A quick example might look like this: