允许Windows服务与桌面交互

问题描述 投票:19回答:3

如何通过编程启用 "允许服务与桌面交互"?

在services.msc > Action > Properties > Log On > Allow service to interact with desktop中,我可以启用我的服务与桌面交互。我希望我的服务能够播放声音(MP3,WAV等)。

services.msc > Action > Properties > Log On > Allow service to interact with desktop

c# windows-services desktop
3个回答
35
投票

我在这里要冒昧地尝试从关键词来解释你的问题。今后,请多花些时间来写你的问题,使它们对另一个试图阅读和理解它们的人有意义。

在Windows服务的属性窗口的Log On选项卡下有一个复选框,这个复选框叫做 "允许服务与桌面交互"。 如果你想以编程的方式勾选该框,你需要指定 SERVICE_INTERACTIVE_PROCESS 标志,当您使用 CreateService API。(见 MSDN).

但是,请注意,从Windows Vista开始,严格禁止服务与用户直接交互。

重要的是,服务不能与用户直接交互。 在Windows Vista中,服务不能直接与用户交互。因此,在题为 "使用交互式服务 "一节中提到的技术不应该在新代码中使用。

这个 "功能 "已经被破坏了,传统的智慧决定了你无论如何都不应该依赖它。服务并不是为了提供UI或允许任何类型的直接用户交互。微软从Windows NT的早期就一直告诫大家要避免使用这个功能,因为可能存在安全风险。拉里-奥斯特曼认为,为什么要 始终是个坏主意. 而他是 非独.

一些 可能的 变通办法然而,如果你 绝对 必须具备这一功能。但我强烈要求你仔细考虑它的必要性,并为你的服务探索其他设计。


7
投票

因为服务不是在用户会话的上下文中运行,所以你要创建第二个应用程序来与服务交互。

例如,Microsoft SQL服务器有一个监控工具。这个应用程序在用户会话中运行,并连接到服务,为你提供服务是否在运行的信息,并允许你停止和启动数据库服务。

由于该应用程序确实是在用户会话中运行的,所以你可以通过该应用程序与桌面进行交互。


5
投票

你需要添加serviceinstaller,并在serviceinstaller的commited事件中写下下面的代码。

using System.Management;
using System.ComponentModel;
using System.Configuration.Install;

private void serviceInstaller1_Committed(object sender, InstallEventArgs e)
{
    ConnectionOptions coOptions = new ConnectionOptions();
    coOptions.Impersonation = ImpersonationLevel.Impersonate;
    ManagementScope mgmtScope = new ManagementScope(@"root\CIMV2", coOptions);
    mgmtScope.Connect();
    ManagementObject wmiService;
    wmiService = new ManagementObject("Win32_Service.Name='" + serviceInstaller1.ServiceName + "'");
    ManagementBaseObject InParam = wmiService.GetMethodParameters("Change");
    InParam["DesktopInteract"] = true;
    ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", InParam, null);
}
© www.soinside.com 2019 - 2024. All rights reserved.