創建一個版本的程序,它接受一個
Sam.exe /StopAndStopTheWindowsServiceINeedToSmack
在您的應用程序的啓動,檢查命令行開關。如果存在,則停止/開始。
然後創建它運行的命令行選項,您的應用程序計劃的任務,並擁有最高權限運行選項設置:
然後使用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代碼發佈到公共領域。無需歸屬。