For a while now the installer for my program has used the below code to make my app run with administer privileges. But it seems to have no effect under Windows 7. In Vista it worked beautifully. If I right click the shortcut and tell it to run as Administer, the program will start fine. But by using the below, code it should be made to run the program that way all the time. It doesn't anymore. Does anyone know if Win 7 still uses this key? UAC is also on by the way.
Registry.SetValue(@"HKEY_CURRENT_USER\Software\Microsoft\Windows NT\
CurrentVersion\AppCompatFlags\Layers", "C:\App\app.exe", "RUNASADMIN");
Thanks.
I have an answer/workaround for this question.
First off, I disagree (respectfully) with the comment that using the AppCompatFlags is not a "proper way to configure your application and installer." Modifying this section of the registry is simply mirroring using the Windows GUI to change the Privilege Level of the executable. I find this method easier to implement than adding a manifest file. If the user wants or needs to change the Privilege Level to not Run as Administrator, they can do that easily with the GUI.
Anyway, I had this same problem of trying to set the Privilege Level of the executable to Run as administrator. We know that we can set it with the the GUI:
When the changes are saved, you will find the setting in the registry:
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"C:\\Program Files (x86)\\My Program\\My Program.exe"="RUNASADMIN"
When I set the .exe
to run as administrator using the GUI in this way, it always works.
However, whenever I tried to change the registry directly without going through the GUI, the program just won't run as administrator. The registry shows that I made the change and when I look at the Privilege Level for the executable, Run as administrator is checked as on.
I tried several different ways to make the .exe
run as an administrator by just changing the registry:
.reg
fileAll these methods did the same thing. The registry was changed and the GUI showed the that program should run as an administrator, but the program never runs as an administrator.
The fix that for this problem that I stumbled across is to go ahead and change both the HKCU
key and the HKLM
key with the setting.
[HKEY_CURRENT_USER\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"C:\\Program Files (x86)\\My Program\\My Program.exe"="RUNASADMIN"
[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"C:\\Program Files (x86)\\My Program\\My Program.exe"="RUNASADMIN"
If you change both of these registry sections, then the .exe
will run as an administrator. More importantly, if a different user logs in to the the PC, the program will run as an administrator. This is in spite of the registry change not being made HKCU section for the subsequent user.
I don't know what is going on here, but it is working.