This is not ideal, but you could probably do something like this:
public static bool IsService() { ServiceController sc = new ServiceController("MyApplication"); return sc.Status == ServiceControllerStatus.StartPending; }
The idea is that if you run this while your service is still running, it will always be on hold. If the service is not installed at all, the method will always return false. In a very unlikely edge case, this will lead to a service failure, and someone is trying to start it as an application at the same time.
I don't like this answer, but I think this is probably the best you can do. Itβs really not a good idea to allow the same application to work in the service or application mode - in the end it will be easier if you draw all the common functions in the class library and just create a separate service application. But if for some reason you really need to have your cake and eat it, you can probably combine the IsService method above with Environment.UserInteractive to get the right answer almost all the time.
Aaronaught
source share