在没有UAC提示窗口的情况下,通过C#启动/停止Windows服务

时间:2014-01-09 05:49:04

标签: c# uac

我需要在每天的特定时间从C#代码启动/停止Windows服务。所以我写了一个简单的C#程序。我的程序仅在我以管理员身份运行时才有效。很好我已经编写代码来管理我的程序。

现在我陷入了这样的境地:我的C#代码将exe文件作为“Admin”运行,但UAC窗口显示为program wants to change settings etc msg。

我需要在Windows调度程序下运行c#代码文件,这意味着不需要人工交互。对于UAC窗口,用户需要选择yes。

如何摆脱这种情况或解决这个问题,以便我的程序能够完全实用地执行和停止服务,而无需任何人为干预?

1 个答案:

答案 0 :(得分:1)

创建一个接受

的程序版本
Sam.exe /StopAndStopTheWindowsServiceINeedToSmack

启动应用程序时,请检查命令行开关。如果存在,则停止/开始。

然后创建一个计划任务,使用命令行选项运行您的应用程序,并设置以最高权限运行选项:

enter image description here

然后使用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));
}
  

注意:任何已发布到公共领域的代码。无需归属。