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

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

问题描述

我创建了一个 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".

之后,我的服务可以打开所需的基于窗口的进程.

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(
                @"SYSTEMCurrentControlSetServicesMy Service", true))
        {
            if (ckey != null && ckey.GetValue("Type") != null)
            {
                ckey.SetValue("Type", (((int)ckey.GetValue("Type")) | 256));
            }
        }
    }
}

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

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