简体   繁体   中英

Windows Service start from logged in user c#

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

}

And there is my servicebase:

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 }}

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM