Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create shortcuts programmatically from C# and set "Run as administrator" property

I already know how to create shortcuts programmatically from my C# applications using IWshRuntimeLibrary and WshShellClass. Or I could use IShellLink.

Now, if the user's PC is running Windows Vista or Windows 7, I would like to be able to set the "Run as administrator" property of that shortcut programmactically as well.

Is that possible? If so, how?

alt text

like image 812
JohnB Avatar asked Oct 27 '10 17:10

JohnB


2 Answers

This example is in PowerShell, but is uses the same objects and classes as C#.

Use the following code to get the byte number to 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])  
    } 
}

I got byte number 21 and its value was 34. So this is the script I user:

# Turning on the byte of "Run as Admin"
$lnkBytes = [System.IO.File]::ReadAllBytes($shortCutLocation)
$lnkBytes[21] = 34
[System.IO.File]::WriteAllBytes($shortCutLocation, $lnkBytes)
like image 172
Mor Shemesh Avatar answered Sep 17 '22 17:09

Mor Shemesh


While Doug's answer is the correct solution to this problem, it is not the answer to this specific question...

To set that property on a .lnk, you need to use the IShellLinkDataList COM interface. The great Raymond Chen has c++ sample code on his blog for this

like image 31
Anders Avatar answered Sep 21 '22 17:09

Anders