首页 > 解决方案 > 是否可以将应用程序配置为在 Windows 启动时启动而不需要管理员权限?

问题描述

我有一个WPF应用程序,我想提供一个复选框,用于配置该应用程序是否会在 Windows 启动时启动(或不启动)。

现在,我可以使用它:

void ManageRunOnStartup(bool runOnStartup)
{
    var shortcutPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Startup), "myApp.lnk");
    var shortcutExists = System.IO.File.Exists(shortcutPath);

    if (runOnStartup)
    {
        if (shortcutExists == false)
            CreateShortcut(shortcutPath);
    }
    else if (shortcutExists)
    {
        System.IO.File.Delete(shortcutPath);
    }
}

void CreateShortcut(string shortcutPath)
{
    var appLocation = System.Reflection.Assembly.GetExecutingAssembly().Location;

    var shell = new WshShell();
    var shortcut = shell.CreateShortcut(shortcutPath) as IWshShortcut;
    shortcut.TargetPath = appLocation;
    shortcut.WorkingDirectory = Path.GetDirectoryName(appLocation);
    shortcut.Save();
}

问题是,要在文件夹中写入/删除Environment.SpecialFolder.Startup文件,该应用程序需要管理员权限:(

有没有办法达到相同的结果但不需要管理员权限?

标签: c#.netwindows

解决方案


如果一个程序是否需要管理员权限,首先是 Manifest。Wich 被放入可执行文件中,因此不受影响。

如果您有一些其他代码启动应用程序(如任务调度程序或服务管理器),您当然可以指定较低权限设置/特定用户。如果你得到了它的权利。

也可以在程序启动期间存储一个值并检查它 - 以及程序是否运行提升。然后尝试使用 Elevation 重新启动。Application.Run 有海拔请求。

反过来摆脱提升的权利根本不是一件容易的事。

编辑:这里有一些关于如何以编程方式启动任何提升程序的代码。

using System;
using System.Diagnostics;
using System.IO;

namespace RunAsAdmin
{
    class Program
    {
        static void Main(string[] args)
        {
            /*Note: Running a batch file (.bat) or similar script file as admin
            Requires starting the interpreter as admin and handing it the file as Parameter 
            See documentation of Interpreting Programm for details */

            //Just getting the Absolute Path for Notepad
            string windir = Environment.GetFolderPath(Environment.SpecialFolder.Windows);
            string FullPath = Path.Combine(windir, @"system32\notepad.exe");

            //The real work part
            ProcessStartInfo startInfo = new ProcessStartInfo(FullPath);
            startInfo.Verb = "runas";
            System.Diagnostics.Process.Start(startInfo);
        }
    }
}

推荐阅读