创建一个接受 a 的程序版本
Sam.exe /StopAndStopTheWindowsServiceINeedToSmack
在您的应用启动时,检查命令行开关。如果存在,则停止/开始。
然后创建一个使用命令行选项运行您的应用程序的计划任务,并设置以最高权限运行选项:
然后使用Task Scheduler 2.0 API 以编程方式启动计划任务。
Bonus Chatter:一段代码
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));
}
注意:任何发布到公共领域的代码。无需署名。