views:

43

answers:

2

I need to do the check in a method contained in a shared library that is referenced by a windows forms application and a windows service.

When we do the check in console mode, I must allow potential dialogs. In case of the windows service, I will write messages in the event log instead.

I found many way to do that using compilation directives. Is there a different and more elegant method ?

Thanks

+1  A: 

Yes, it is. At runtime, you might check whether the process parent is services.exe or the current process is svchost.exe. Or you could query the service control manager using WinApi whether your service is started and the current process id is equal to the one of the started service.

This answer has some sample code in C#:

How do we tell if a C++ application is launched as a Windows service?

0xA3
+2  A: 

You can check Environment.UserInteractive property which will return false if your application is running as a windows service.

Chris Taylor
Will it returns false also when "Allow Service to interact with desktop" is checked ?
Pierre 303
@Pierre 303: `Environment.UserInteractive` will return `true` if "Allow Service to interact with desktop" is checked.
0xA3
@Pierre 303. As 0xA3 has said, Environment.UserInteractive will return true if the service is set to 'Allow Service to interact with desktop'. If you need to support interacting with the desktop but still restrict your logs from showing in the UI, then you should probably go with something along the lines of the solution proposed by 0xA3.
Chris Taylor