簡體   English   中英

以編程方式從C#創建快捷方式並設置“以管理員身份運行”屬性

[英]Create shortcuts programmatically from C# and set “Run as administrator” property

我已經知道如何使用IWshRuntimeLibraryWshShellClass從我的C#應用​​程序中以編程方式創建快捷方式。 或者我可以使用IShellLink

現在,如果用戶的PC運行的是Windows Vista或Windows 7,我希望能夠同時設置該快捷方式的“以管理員身份運行”屬性。

那可能嗎? 如果是這樣,怎么樣?

替代文字

雖然道格的答案是解決這個問題的正確方法,但這不是這個具體問題的答案......

要在.lnk上設置該屬性,需要使用IShellLinkDataList COM接口。 偉大的Raymond Chen 在他的博客上c ++示例代碼

此示例位於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)

您需要為應用程序創建清單文件 ,以使其以管理員權限請求運行。 這是一個很好的教程,你可以遵循。

請享用!

使用此方法,您可以創建一個設置為“以管理員身份運行”屬性的快捷方式:

    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 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM