Open as administrator only the first time in Delphi.

3

I put a method on my system to change the registry by starting it with windows, so the executable must be run in administrator mode. The problem is that every time the system starts, the application opens and shows the message asking if the user wants to start as an administrator, which seems a bit annoying to me.

The question I ask is: Is there any way to open the application in administrator mode only the first time? or maybe check if the registry exists in windows and if it does run in normal mode?

    
asked by anonymous 15.12.2016 / 14:48

3 answers

2

As the usage will be occasional, you can implement a function in C to call by Delphi only when you need elevation:

#include "windows.h"

SHELLEXECUTEINFO lpExecInfo;
memset(&lpExecInfo, 0, sizeof(SHELLEXECUTEINFO));

lpExecInfo.cbSize = sizeof(SHELLEXECUTEINFO);
lpExecInfo.lpFile = // aqui vai o nome do executável (no caso, o próprio aplicativo);
lpExecInfo.lpDirectory = // aqui vai o caminho no qual ele deve ser executado;
lpExecInfo.lpVerb = "runas";
lpExecInfo.lpParameters = "runasadmin";
lpExecInfo.nShow = SW_NORMAL;
lpExecInfo.fMask = 0;
lpExecInfo.hwnd = NULL;

ShellExecuteEx(&lpExecInfo); // retorna verdadeiro se o usuário aceitou

In this case, you do not specify in the manifest that you need administrative privileges, and only call the above function in case you need to do something like admin.

If the result of ShellExecuteEx is true, you can quit the current instance because the user has accepted UAC and is already running an admin version in parallel.

    
27.12.2016 / 02:35
2

It is not possible to open the application with privileges only the first time if it already loads the manifest to open elevated. Also not interesting you start the application high and then run it without privileges.

Maybe it would be better to do the following:

  • Configure the installation of your application.
  • During execution validate if the application is at startup and, if not, notify the user. Then run another process / application to do this configuration.
  • 26.12.2016 / 21:10
    1

    In project options / Application in the Manifest File section, check the option:

    Enable Administrator Privileges to resolve.

        
    15.12.2016 / 18:02