5

我有以下简单的服务程序:

using System.Diagnostics;
using System.ServiceProcess;

namespace BasicService
{
    public partial class Service1 : ServiceBase
    {
        public Service1()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo
                                                    {
                                                        Verb = "runas",
                                                        UserName = "jdoe",
                                                        Password = "XXXXXXX".ConvertToSecureString(),
                                                        Domain = "abc.com",
                                                        UseShellExecute =false,
                                                        FileName = "notepad.exe"
                                                    };
            Process.Start(processStartInfo);
        }

        protected override void OnStop()
        {
        }
    }
}

我将其用作我的服务安装程序:

using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;

namespace BasicService
{
    [RunInstaller(true)]
    public class ProjectInstaller : Installer
    {
        private readonly ServiceProcessInstaller _process;
        private readonly ServiceInstaller _service;

        public ProjectInstaller()
        {
            _process = new ServiceProcessInstaller {Account = ServiceAccount.LocalSystem};
            _service = new ServiceInstaller
                           {
                               ServiceName = "BasicService",
                               Description = "Just a testing service.",
                               StartType = ServiceStartMode.Automatic,
                           };

            Installers.Add(_process);
            Installers.Add(_service);
        }
    }
}

如果我在没有指定动词、用户名、密码、域和 useshellexecute 的情况下运行此服务,那么一切都运行得很好。如上所示,一旦我指定了这些值,我就会得到以下信息:

无法启动服务。System.ComponentModel.Win32Exception (0x80004005):访问被拒绝在 System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) 在 System.Diagnostics.Process.Start() 在 System.Diagnostics.Process.Start(ProcessStartInfo startInfo) 在 BasicService.Service1 C:\BasicService\BasicService\Service1.cs 中的 .OnStart(String[] args):System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback 的第 24 行(对象状态)

有任何想法吗?

4

1 回答 1

3

从 Windows Vista 开始,服务不能简单地显示 ui 或与用户交互。
http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx

因此,要从您的服务运行 GUI 应用程序,您需要使用 CreateProcessAsUser,它在 .NET 中不直接可用。所以你必须依赖 Pinvoke,有点类似于这里描述的

http://blogs.msdn.com/b/alejacma/archive/2007/12/20/how-to-call-createprocesswithlogonw-createprocessasuser-in-net.aspx

于 2012-02-27T08:20:29.893 回答