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

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

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

alt text

有帮助吗?

解决方案

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

要在 .lnk 上设置该属性,您需要使用 IShellLink数据列表 COM接口。伟大的陈雷蒙德 他的博客上的 c++ 示例代码 为了这

其他提示

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

享受!

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

使用以下代码获取 activtae 的字节数:

# 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)

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

    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);
            }
    }

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top