我有以下简单的服务程序:
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.Win32异常(0x80004005):访问在被拒绝System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfostartInfo)的System.Diagnostics.Process.Start()位于的System.Diagnostics.Process.Start(ProcessStartInfo startInfo)中的BasicService.Service1.OnStart(String[]args)C: \ BasicService\ BasicServices\Service1.cs:第24行System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(对象状态)
有什么想法吗?
由于Windows Vista,服务不能简单地显示ui或与用户交互
http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx
因此,要从您的服务运行GUI应用程序,您需要使用CreateProcessAsUser,这在.NET中是不直接可用的
http://blogs.msdn.com/b/alejacma/archive/2007/12/20/how-to-call-createprocesswithlogonw-createprocessasuser-in-net.aspx