以编程方式从C#创建快捷方式并设置“以管理员身份运行”属性

时间:2010-10-27 17:46:19

标签: c# windows-7 uac shortcut

我已经知道如何使用IWshRuntimeLibraryWshShellClass以编程方式从我的C#应用​​程序创建快捷方式。或者我可以使用IShellLink

现在,如果用户的PC运行的是Windows Vista或Windows 7,我希望能够同时设置该快捷方式的“Run as administrator”属性。

这可能吗?如果是这样,怎么样?

alt text

4 个答案:

答案 0 :(得分:4)

虽然道格的答案是解决这个问题的正确方法,但这不是这个具体问题的答案......

要在.lnk上设置该属性,您需要使用IShellLinkDataList COM接口。伟大的雷蒙德陈有c++ sample code on his blog为此

答案 1 :(得分:3)

您需要为应用程序创建清单文件,以使其以管理员权限请求运行。 Here is a nice tutorial you can follow.

享受!

答案 2 :(得分:3)

此示例位于PowerShell中,但使用与C#相同的对象和类。

使用以下代码获取要激活的字节编号:

# Find the missing admin byte (use this code, when changing the link):
$adminon = [System.IO.File]::ReadAllBytes($shortCutLocation)
$adminof = [System.IO.File]::ReadAllBytes($shortCutLocation)
for ($i = 0; $i -lt $adminon.Count; $i++) { 
    if ($adminon[$i] -ne $adminof[$i]) { 
        Write-Host Location: $i Value: $($adminon[$i])  
    } 
}

我得到第21个字节,其值为34。 所以这是我用户的脚本:

# Turning on the byte of "Run as Admin"
$lnkBytes = [System.IO.File]::ReadAllBytes($shortCutLocation)
$lnkBytes[21] = 34
[System.IO.File]::WriteAllBytes($shortCutLocation, $lnkBytes)

答案 3 :(得分:0)

使用这种方法,您可以创建一个设置了“以管理员身份运行”属性的快捷方式:

    void CreateShortcut(string shortcutPath, string sourcePath, bool runAsAdmin, params string[] args)
    {
        var shortcut = new IWshShell_Class().CreateShortcut(shortcutPath) as IWshShortcut;
        shortcut.TargetPath = System.IO.Path.GetFullPath(sourcePath);
        shortcut.Arguments = "\"" + string.Join("\" \"", args) + "\"";
        shortcut.Save();

        if (runAsAdmin)
            using (var fs = new FileStream(shortcutPath, FileMode.Open, FileAccess.ReadWrite))
            {
                fs.Seek(21, SeekOrigin.Begin);
                fs.WriteByte(0x22);
            }
    }

以管理员身份运行的信用属于here