简体   繁体   中英

Is it possible to detect if the main application thread is running as a Windows Service without using a compilation directive?

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

您可以检查Environment.UserInteractive属性,如果您的应用程序作为Windows服务运行,则该属性将返回false。

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM