简体   繁体   English

是否可以在不使用编译指令的情况下检测主应用程序线程是否作为Windows服务运行?

[英]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.

相关问题 运行 Windows 服务应用程序而不安装它 - Running Windows Service Application without installing it 使用Windows Service检查应用程序是否正在运行 - Checking if an application is running using Windows Service Windows服务检测应用程序无响应? - Windows Service Detect Application Not Responding? Windows Service从主线程调用方法 - Windows Service invoke method from main thread 在Windows Phone Silverlight应用程序8 / 8.1中同步等待Web服务时,主线程冻结 - Main thread freezes when waiting for Web service synchronously in Windows Phone Silverlight Application 8/8.1 使用Log4Net的Windows Service运行应用程序 - Windows Service running application using Log4Net 是否可以使用没有 windows 服务的服务帐户(域)在不同的用户(模拟)下运行代码? - Is running code under a different user (impersonation) possible with a service account (domain) without a windows service? 在Windows Service中运行线程时出现错误1607 - Error 1607 when running thread in windows service 在Windows服务中运行的线程中最终不会执行 - Finally is not executed when in a Thread running in a Windows Service 在带有Windows窗体的Designer生成的代码中使用#if指令进行条件编译 - Using the #if directive in designer generated code with windows forms for conditional compilation
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM