2014-01-09 29 views
0

我需要在特定的時間每天開始/停止從C#代碼的Windows服務。所以我寫了一個簡單的C#程序。我的程序只在我以管理員身份運行時才起作用。它很好,我寫了代碼來管理我的程序。通過C#啓動/停止Windows服務與管理沒有UAC提示窗口運行

現在我陷入了這種情況,即我的C#代碼運行exe文件爲「Admin」,但UAC窗口顯示爲program wants to change settings etc msg。

我需要我的c#代碼文件在windows scheduler下運行,這意味着不需要人爲交互。至於UAC窗口,用戶需要選擇是。

我該如何擺脫這個問題或解決問題,以便我的程序能夠在沒有任何人機交互的情況下完全務實地執行和停止服務?

回答

1

創建一個版本的程序,它接受一個

Sam.exe /StopAndStopTheWindowsServiceINeedToSmack 

在您的應用程序的啓動,檢查命令行開關。如果存在,則停止/開始。

然後創建它運行的命令行選項,您的應用程序計劃的任務,並擁有最高權限運行選項設置:

enter image description here

然後使用Task Scheduler 2.0 API以編程方式啓動的計劃任務。

獎金看點:代碼塊

public Form1() 
{ 
    InitializeComponent(); 

    //Ideally this would be in program.cs, before the call to Application.Run() 
    //But that would require me to refactor code out of the Form file, which is overkill for a demo 
    if (FindCmdLineSwitch("StopAndStopTheWindowsServiceINeedToSmack", true)) 
    { 
     RestartService("bthserv"); //"Bluetooth Support Service" 
     Environment.Exit(0); 
    } 
} 

private bool FindCmdLineSwitch(string Switch, bool IgnoreCase) 
{ 
    foreach (String s in System.Environment.GetCommandLineArgs()) 
    { 
     if (String.Compare(s, "/" + Switch, IgnoreCase) == 0) 
      return true; 
     if (String.Compare(s, "-" + Switch, IgnoreCase) == 0) 
      return true; 
    } 
    return false; 
} 

我們重新啓動服務:

private void RestartService(String ServiceName) 
{ 
    TimeSpan timeout = TimeSpan.FromMilliseconds(30000); //30 seconds 

    using (ServiceController service = new ServiceController(ServiceName)) 
    { 
     try 
     { 
      service.Start(); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.Message, "Error stopping service"); 
      return; 
     } 
     service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); 

     try 
     { 
      service.Start(); 
     } 
     catch (Exception e) 
     { 
      MessageBox.Show(e.Message, "Error starting service"); 
      return; 
     } 
     service.WaitForStatus(ServiceControllerStatus.Stopped, timeout); 
    } 
} 

獎勵:檢查,如果你正在運行高架:

private Boolean IsUserAnAdmin() 
{ 
    //A user can be a member of the Administrator group, but not an administrator. 
    //Conversely, the user can be an administrator and not a member of the administrators group. 

    //Check if the current user has administrative privelages 
    var identity = WindowsIdentity.GetCurrent(); 
    return (null != identity && new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator)); 
} 

備註:A NY代碼發佈到公共領域。無需歸屬。