我怎样才能在代码中配置我的Windows服务来访问桌面? [英] How can I configure my windows service in the code to access the desktop?

查看:144
本文介绍了我怎样才能在代码中配置我的Windows服务来访问桌面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个Windows服务。我想打开基于从这项服务中应用程序的一些窗口。

I have created an windows service. I want to open some windows based application from this service.

但我的Windows服务无法启动​​桌面应用程序。为使访问我不得不做以下步骤:

But my windows service is unable to start desktop applications. To enable the access I had to do the following steps:


  1. 打开管理工具的服务

  1. Opened the administrative tool "Services"

右键点击我的服务,只好选择属性

Right clicked on my service and had to select "properties"

然后,选择允许服务与桌面交互。

Then in the "Log On" tab, selected "Allow service to interact with desktop".

这是我的服务可以打开所需的基于Windows的程序后。

After that my service can open desired windows based processes.

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

Can I configure my windows service in the code (C#) to access the desktop so that I won't have to change the access permission manually after installation?

推荐答案

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

In .NET you can override the OnCommited method of the service installer class to configure the service to access the desktop. The code will look as follows:

[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));
            }
        }
    }
}

这篇关于我怎样才能在代码中配置我的Windows服务来访问桌面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆