Windows 服务从登录用户启动 c# [英] Windows Service start from logged in user c#

查看:131
本文介绍了Windows 服务从登录用户启动 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个 Windows 服务(正在运行),但它在 SYSTEM 用户上运行,我希望它在我当前登录的用户上运行.

I made a windows service (which is working), but it is running on the SYSTEM user and I want it to run on my current logged in user.

这是我的服务安装程序类:

Here is my service installer class:

[RunInstaller(true)]
class CloudManagerServiceInstaller : Installer
{
    public CloudManagerServiceInstaller()
    {
        var serviceInstaller = new ServiceInstaller();
        var serviceProcessInstaller = new ServiceProcessInstaller();

        serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.User;
        serviceProcessInstaller.Username = Environment.MachineName + "\\carl";

        serviceInstaller.DisplayName = "Z";
        serviceInstaller.StartType = ServiceStartMode.Manual;

        serviceInstaller.ServiceName = "Z";

        this.Installers.Add(serviceInstaller);
        this.Installers.Add(serviceProcessInstaller);
    }

}

还有我的服务库:

class CloudManagerServiceBase : ServiceBase
{
    public int i = 0;
    private System.Timers.Timer _timer;
    private int m = 2;
    public CloudManagerServiceBase()
    {
        this.ServiceName = "ZSCloudManager";
    }

    protected override void OnStart(string[] args)
    {
        base.OnStart(args);

        _timer = new System.Timers.Timer(m * 60 * 1000); // every m minutes
        _timer.Elapsed += _timer_Elapsed;
        _timer.Start(); // <- important



    }

    void _timer_Elapsed(object sender, ElapsedEventArgs e)
    { do work }}

我在另一个程序的帮助下安装了该服务.我可以这样编写服务还是必须遵循这些说明-> http://blogs.msdn.com/b/winsdk/archive/2009/07/14/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later.aspx如果是这样的话,你能不能给我一个代码片段,因为我不完全理解这一点.

I install the service with the help of another progamm. Can I write the service like that or do I have to follow these instructions -> http://blogs.msdn.com/b/winsdk/archive/2009/07/14/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later.aspx If thats the case then can you please give me a code snippet, because i dont fully understand this.

推荐答案

我放弃了手动操作,而是使用 Visual Studio 中的服务预设来实现.我刚刚将它添加到预设中(在 projectInstaller 类中):

I gave up doing it manually and made it with the serivice preset from Visual Studio. I just added this to the preset (in the projectInstaller class):

public ProjectInstaller()
{
    InitializeComponent();
    serviceProcessInstaller1.Username = ".\\" + Environment.UserName;
}

并将 serviceProcessInstaller 中的 Property Account 设置为user".之后,您可以在 Service 类中添加您的代码.对我来说效果很好.

And set the Property Account from serviceProcessInstaller to "user". After that you can add your code in the Service class. It works fine for me.

这篇关于Windows 服务从登录用户启动 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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