Is there a way for an .NET library to detect whether or not it is being run as a service?
My library can be run either way. But when its run as a service, developer
The answer by 0xA3 to this question actually contains C# code to query the SCM, much like Rob Parker describes in his answer.
You can add the Microsoft.Extensions.Hosting.WindowsServices NuGet package and use the WindowsServiceHelpers.IsWindowsService()
helper method.
For Linux you can use Microsoft.Extensions.Hosting.Systemd and the SystemdHelpers.IsSystemdService()
method.
You should probably check that you are running in session zero (at least if you are targeting Vista). You can use WTSRegisterSessionNotification
, like in this sample:
[DllImport("kernel32.dll")]
private static extern int WTSGetActiveConsoleSessionId();