In .NET Framework 4.6.2, if I double-click an exe that's registered as a Windows service, I see this message:
Great! Prevents bad things from happening.
Now I'm on .NET 8 and I've written a Windows service that is a BackgroundTask with a Worker... how can I emulate this same behavior where someone tries to run it directly from the EXE? I want to prevent the thing from running unless it's a service. Can this be done?
This question is practically important.
This problem and related problems can be solved by using the property System.Environment.UserInteractive
.
If the value of this property is true
during runtime, the application was loaded and started as a normal application of any kind, for example, via the system Shell. Otherwise, it was started as a service, that is, loaded and started by the service controller.
In particular, you can do even better: you can create an application that can be started and work correctly in both ways. In the interactive mode, it can even execute some windowed UI. Also, if you share most of the code between interactive and service mode, you can debug this code the same way you do it for the normal (interactive application), which is a lot easier.
For example, you can check the property in your Main
and conditionally execute one of two branches:
class Program {
// ...
static void Main() {
if (System.Environment.UserInteractive)
StartUI();
else
StartService();
} //Main
}