Search code examples
c#processcompatibilityprivileges

Change executable compatibility with code


I have a file MyUtilities.exe.

When I run: Process.Start("MyUtilities.exe","SomeParameter");

the exit code of that process is 0 (OK) if it is run WITHOUT admin privileges. If I run that code as an administrator exit code is 1!

Since I did not create MyUtilities.exe I cannot modify it.

In the end I need to run Process.Start("MyUtilities.exe","SomeParameter"); as an administrator And have it return an exit code = 0. The way I managed to do that was by changing its compatibility to:

enter image description here

(Right click on the file->Properties->Compatibility->Run this program as an administrator)

after changing that now I am able to run Process.Start("MyUtilities.exe","SomeParameter"); as an administrator and have it return an exit code of 0.

So my question is how can I change the compatibility of that file with code so that I don't have to tell users to right click on the file then change the settings.


Solution

  • This looks pretty simple. Just add a value to the registry.

    Key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers -or- HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers

    Name: f:\ull\path\to\executable.exe

    Value: RUNASADMIN

    Here's how you would do this in code. If you write to HKCU, the calling process will not need to be running as Administrator.

    static void SetRunAsAdmin(string exeFilePath)
    {
        var key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers", true);
        if (key == null)
            throw new InvalidOperationException(@"Cannot open registry key HKCU\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers.");
        using (key)
            key.SetValue(exeFilePath, "RUNASADMIN");
    }