2014-12-05 39 views
0

我做了一個windows服務(這是工作),但它運行在SYSTEM用戶,我希望它在我當前登錄的用戶上運行。Windows服務從登錄用戶開始c#

這裏是我的服務安裝程序類:

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

} 

而且還有我的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 }} 

我與另一progamm的幫助下安裝該服務。 我可以寫這樣的服務嗎?或者我必須遵循這些說明 - >http://blogs.msdn.com/b/winsdk/archive/2009/07/14/launching-an-interactive-process-from-windows-service-in-windows-vista-and-later.aspx 如果是這種情況,那麼請給我一個代碼片段,因爲我沒有完全理解這一點。

+0

一個windows服務根本不需要用戶登錄,可能有多個用戶登錄。那麼你是什麼意思,你想運行該服務作爲「當前登錄的用戶」。你想永遠以特定的用戶身份運行嗎? – 2014-12-05 15:09:54

+0

我想你想從Windows服務更改爲在用戶登錄時運行的應用程序。 – AWinkle 2014-12-05 15:32:43

+0

是@Ben Robinson我希望服務始終以特定用戶身份運行。 – carlilord 2014-12-08 19:17:35

回答

1

我放棄了手動操作,並使用Visual Studio中的Serve Preset進行設置。我只是說這預設(在projectInstaller類):

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

而且從serviceProcessInstaller到「用戶」設置屬性帳戶。之後,您可以在Service類中添加代碼。這對我來說可以。