[英]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. 我需要在Windows窗体应用程序和Windows服务引用的共享库中包含的方法中进行检查。
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.
如果使用Windows服务,我将在事件日志中写入消息。
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.
在运行时,您可能会检查进程父进程是services.exe还是当前进程是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.
或者,您可以使用WinApi向服务控制管理器查询您的服务是否已启动并且当前进程ID是否等于已启动的服务之一。
This answer has some sample code in C#: 这个答案在C#中有一些示例代码:
How do we tell if a C++ application is launched as a Windows service?
我们如何确定C ++应用程序是否作为Windows服务启动?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.