Search code examples
cwinapiuacshellexecuteex

Bring UAC window to top using ShellExecuteEx()


I am using Microsoft Visual Studio 2010 and I am writing my code in C/C++.

I have code which automatically starts my installation process. Installation process requires UAC in this case, so I use ShellExecuteEx() API function with runas verb:

hWindow = InstallCreateWindow(NULL);

execInfo.cbSize         = sizeof(execInfo);
execInfo.lpVerb         = _strdup("runas");
execInfo.hwnd           = hWindow;
execInfo.lpFile         = szPath;
execInfo.lpParameters   = szParams;
execInfo.fMask          = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_FLAG_NO_UI;

Sleep(1000);

SetActiveWindow(hWindow);

if(ShellExecuteEx(&execInfo))
    return execInfo.hProcess;

if(GetLastError() == ERROR_CANCELLED)
{
    // user answered NO to UAC prompt
}

InstallCreateWindow() function creates information window and it also creates separate window message thread. Window is visible, topmost and it responds to messages. I have to create it because I've read that correct hwnd parameter in SHELLEXECUTEINFO structure is required to keep UAC prompt window on top.

But this does not work. Sometimes UAC window runs maximized, but mainly it is minimized and highlighted in the taskbar. Is there a method to bring UAC window to top in any case?


Solution

  • JUST TO MARK IT AS ANSWERED

    If the program that called ShellExecuteEx does not have foreground activation, then the UAC dialog cannot take activation, so it has to wait until the use activates it. Raymond Chen