I'm trying to make a C program that modifies my host file, but I can't just straight up open the file with the program, because Windows blocks it. Is there any way that I can make the program request administrative privileges within the code, or any script I can use to start the program in admin mode?
2 Answers
Right clicking is a solution that allows you to run any program with Administrator privileges. That includes ticking the box in "Properties".
On Windows 7 and later, you can also rename your program so that its name contains setup
(like hosts_setup.exe
), and it'll automatically be run in Administrator mode (brings up the UAC prompt) if double-clicked in Explorer. Note this only works from double-clicking in Explorer.
You can also take a look at How can I run a child process that requires elevation and wait? . It calls WinAPI and is a fairly native approach. The best solution is to add it in menifest so your program requests Admin at startup.

- 35,554
- 7
- 89
- 134
-
I am not a Windows user, but I need to ask: does this mean that after you run it like that the user is asked to input the windows administrator password. Or I am wrong? – Michi Nov 18 '17 at 06:57
-
@Michi It brings up the UAC prompt. Nothing slips past that. – iBug Nov 18 '17 at 06:58
-
@Michi, if manifested as `requireAdministrator`, then `CreateProcess` fails with `ERROR_ELEVATION_REQUIRED` if the caller isn't already elevated. The caller can retry via `ShellExecuteEx` with the "runas" action. This sends the request to a system service named "Application Information", which runs consent.exe (the UAC dialog) on the secure Desktop of the requesting Session. If it gets consent, the service calls `CreateProcessAsUser` to run the elevated process in the given Session. Console applications allocate an elevated console (conhost.exe instance) instead of inheriting the parent's. – Eryk Sun Nov 18 '17 at 12:18
-
The manifest can be added externally, without requiring a tool such as mt.exe to embed it as a resource in the executable. If the file is named "foo.exe", then name the manifest beside it as "foo.exe.manifest". – Eryk Sun Nov 18 '17 at 12:22
Shoot, okay, seconds after posting this question, I found a solution. It turns out that you can right click the executable, click properties, and on the compatibility tab, select "Run this program as administrator". Just in case anyone else needed this information.

- 9
- 1
- 4
-
-
It answers the first sentence, but avoids the second by external means. – David C. Rankin Nov 18 '17 at 06:51