Créer des raccourcis de programmation C # et ensemble « Exécuter en tant qu'administrateur » propriété

StackOverflow https://stackoverflow.com/questions/4036081

  •  26-09-2019
  •  | 
  •  

Question

Je sais déjà comment créer des raccourcis programme de mes applications C # à l'aide IWshRuntimeLibrary et WshShellClass. Ou je pourrais utiliser IShellLink.

Maintenant, si fonctionne sous Windows Vista ou Windows 7 PC de l'utilisateur, je voudrais être en mesure de régler la « Exécuter en tant qu'administrateur » de ce raccourci programmactically ainsi.

Est-ce possible? Si oui, comment?

text alt

Était-ce utile?

La solution

Alors que la réponse de Doug est la bonne solution à ce problème, ce n'est pas la réponse à cette question spécifique ...

Pour définir cette propriété sur un .lnk, vous devez utiliser le IShellLinkDataList COM interface. Le grand Raymond Chen a c ++ exemple de code sur son blog pour cette

Autres conseils

Vous devez créer un fichier manifest pour votre application afin d'obtenir à terme la demande en tant que privilèges d'administrateur. Voici un tutoriel bien vous peut suivre.

Amusez-vous!

Cet exemple est PowerShell, mais utilise les mêmes objets et les classes que C #.

Utilisez le code suivant pour obtenir le numéro d'octet à 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 eu nombre d'octets 21 et sa valeur a été 34. Donc, c'est I utilisateur du script:

# Turning on the byte of "Run as Admin"
$lnkBytes = [System.IO.File]::ReadAllBytes($shortCutLocation)
$lnkBytes[21] = 34
[System.IO.File]::WriteAllBytes($shortCutLocation, $lnkBytes)

Avec cette méthode, vous pouvez créer un raccourci qui est définie la propriété « Exécuter en tant qu'administrateur »:

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

Crédit pour l'exécution en tant que section admin appartient à ici

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top