How to grant administrator privileges to Windows applications with CMake

administrator_privileges_uac

Sometimes happens that you need grant administrator privileges to Windows applications because you need to access to some kind of hardware feature, launch a child process within your application or anything else. Otherwise, your application will not be able to perform these actions.

For that, you need to create a manifest file in which you have to indicate that you application should ask the user for administrator privileges and, after that, embed the file in your application executable.

If you are also using CMake and you want to include all this tricky stuff in your build process, keep reading.

The first thing that you need is to create a manifest file with the following structure:

And change the name and the description of your application.

Notice that in the security section of this file, your are requiring administrator privileges.

If you want to read more information about how the manifest file works and what means each one of the fields, you can check the Microsoft’s documentation:

The next step is to embed the manifest file in your application executable. For that you need the application mt, included in the Windows SDK.

Windows SDK is a collection of tools to deploy applications in Windows environments. Download and install it from the following links depending on your operating system:

Now that you have installed the Windows SDK, it is time to run the following command to embed the manifest file:

Where manifest.xml is your manifest file, and application.exe is your application executable.

The result of running this command should be as follows:

You can pass the parameter -nologo to mt if you want to omit this message. That is very useful if you are running this command as part of a build process and you do not want to show it in the output.

Now, try to run your application and check that a confirmation message appears in the screen asking you to grant administrator privileges. If the message appears, it means that it works! ^_^

The last step will be to include this command in CMake to run it each time that we build the application.

Find the command add_executable in your CMakeList.txt to check what is the name of your application:

Create a custom command dependant on the executable to run the mt command and embed the manifest file:

Where again manifest.xml is your manifest file, and application.exe is your application executable.

Notice the use of ${PROJECT_SOURCE_DIR} and ${PROJECT_BINARY_DIR} for figure out where are the sources and binary folders.

That is all! Now your application will ask for administrator privileges each time it is run.

Tweet about this on Twitter0Share on Facebook0Share on Google+0Share on LinkedIn0Buffer this pageEmail this to someonePrint this page

Leave a Reply