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

Joh*_*hnB 3 c# uac shortcut windows-7

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

现在,如果用户的PC运行的是Windows Vista或Windows 7,我也希望能够通过编程方式设置该快捷方式的“以管理员身份运行”属性。

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

替代文字

Dou*_*oug 5

您将需要为您的应用程序创建一个清单文件,以便让它请求以管理员权限运行。 这是一个很好的教程,您可以遵循。

享受!


And*_*ers 5

道格(Doug)的答案是解决此问题的正确方法,但不是该特定问题的答案...

要在.lnk上设置该属性,您需要使用IShellLinkDataList COM接口。伟大的Raymond Chen 在他的博客上为此提供了c ++示例代码

  • 在向他展示如何将接口声明放入他的C#程序之前,它不是很有用。 (2认同)

Mor*_*esh 5

此示例在 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])  
    } 
}
Run Code Online (Sandbox Code Playgroud)

我得到的字节数为 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)
Run Code Online (Sandbox Code Playgroud)


ssz*_*ssz 5

使用此方法您可以创建一个快捷方式,其\xe2\x80\x9c以管理员身份运行\xe2\x80\x9d属性已设置:\n首先,您需要添加对“Windows脚本宿主对象模型”库的引用,它是COM 库,因此在项目中,右键单击引用转到 COM 部分,然后添加该库。

\n
using System;\nusing System.Linq;\nusing System.IO;\nusing System.Text;\nusing System.Collections;\nusing System.Collections.Generic;\nusing IWshRuntimeLibrary;\n\nclass Solution\n{\n\n\n    static void CreateShortcut(string shortcutPath, string sourcePath, bool runAsAdmin, params string[] args)\n    {\n        var shortcut = new IWshShell_Class().CreateShortcut(shortcutPath) as IWshShortcut;\n        shortcut.TargetPath = System.IO.Path.GetFullPath(sourcePath);\n\n        shortcut.Arguments = "\\"" + string.Join("\\" \\"", args) + "\\"";\n        shortcut.Save();\n\n        if (runAsAdmin)\n            using (var fs = new FileStream(shortcutPath, FileMode.Open, FileAccess.ReadWrite))\n            {\n                fs.Seek(21, SeekOrigin.Begin);\n                fs.WriteByte(0x22);\n            }\n    }\n\n    static void Main(string[] args)\n    {\n        CreateShortcut(Directory.GetCurrentDirectory() + "\\\\" + "shortcutName" + ".lnk", @"C:\\...... path to file ... .exe", true);\n\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

以管理员身份运行部分的功劳属于这里

\n