Question

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

Was it helpful?

Solution

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

OTHER TIPS

You will need to create a manifest file for your application in order to get it to request run as an administrator privileges. Here is a nice tutorial you can follow.

Enjoy!

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)

With this method you can create a shortcut that “Run as administrator” property is set:

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

Credit for run as admin section belongs to here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top