如何在代码中配置我的Windows服务以访问桌面?

我创建了一个Windows服务。 我想从这个服务打开一些基于Windows的应用程序。

但我的Windows服务无法启动桌面应用程序。 要启用访问权限,我必须执行以下步骤:

  1. 打开管理工具“服务”

  2. 右键单击我的服务,必须选择“属性”

  3. 然后在“登录”选项卡上,选择“允许服务与桌面交互”。

之后,我的服务可以打开所需的基于Windows的进程。

我可以在代码(C#)中配置我的Windows服务来访问桌面,这样我就不必在安装后手动更改访问权限了吗?

在.NET中,您可以覆盖服务安装程序类的OnCommited方法,以配置访问桌面的服务。 代码如下:

 [RunInstaller(true)] public partial class ProjectInstaller : Installer { private ServiceProcessInstaller serviceProcessInstaller; private ServiceInstaller serviceInstaller; public ProjectInstaller() { InitializeComponent(); // adjust configuration to whatever is needed serviceInstaller = new ServiceInstaller(); serviceInstaller.ServiceName = "My Service"; serviceInstaller.DisplayName = "My Service"; serviceInstaller.StartType = ServiceStartMode.Manual; this.Installers.Add(serviceInstaller); serviceProcessInstaller = new ServiceProcessInstaller(); serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalSystem; serviceProcessInstaller.Password = null; serviceProcessInstaller.Username = null; this.Installers.Add(serviceProcessInstaller); } protected override void OnCommitted(IDictionary savedState) { base.OnCommitted(savedState); // The following code sets the flag to allow desktop interaction // for the service // using (RegistryKey ckey = Registry.LocalMachine.OpenSubKey( @"SYSTEM\CurrentControlSet\Services\My Service", true)) { if (ckey != null && ckey.GetValue("Type") != null) { ckey.SetValue("Type", (((int)ckey.GetValue("Type")) | 256)); } } } } 

只是……不要。 这不是服务的工作。 对于这项工作,您应该使用用户应用程序(可能在他们的启动时)(如有必要)通过IPC与服务进行通信。 我相信计划是在某些时候使用户界面无法使用UI(从Vista开始?我很久以前就停止了服务<=>桌面)。

考虑因素:

  • 如果您有多个用户登录(快速用户切换)怎么办?
  • 如果您有多个RDP会话怎么办?

你提议的只是真正扩展为1,并且可能不是如果你认为“会话0”被保留用于某些系统上的管理员使用的事件(因此交互式用户不一定在会话0上)。