I have some windows services written in C#. When somebody stops or starts the service, I would like to be able to determine who it was and log that information.
I t
Event ID 7040 - covers Service start type change (eg disabled, manual, automatic)
Event ID 7036 - covers Service start/stop
For others that have PowerShell, you can use this:
get-eventlog -source "Service Control manager" -LogName System | select message, timegenerated, username | Out-GridView
Within the Event Viewer (Control Panel | Administrative Tools | Event Viewer) on the System tab the Service Control Manager logs who started and stop each event. I've just tested this myself and viewed the results. This leads me to two things:
Hope that leads you to your solution.
You can enable auditing according to this article
http://windowsitpro.com/systems-management/access-denied-auditing-users-who-might-be-starting-and-stopping-services
Additionally, it may be a good idea to alert email to yourself in OnStop() method.
There probably isn't a way. Any of the normal .NET ways that you get at the environment's user are going to return the user whose credentials the service runs with (which will typically be SYSTEM, LOCAL SERVICE, NETWORK SERVICE, etc).
How I'd probably do it is poll the system to see if a user is logged in, and assume that user did it. Of course, this discounts services that are shut down by the system for some reason (presumably your service would not be), and can only help you narrow it down if more than one user is logged in at one time (but then, you could always log both of them).