Specifying whether elevation is required
is typically something that is the responsibility of the program.
This is done by
adding a requestedExecutionLevel
element to your manifest.
(Bart De Smet shows you how.
Calvin Hsia does the same for your Visual FoxPro programs.)
But if the program you’re running doesn’t have such a manifest—maybe
it’s an old program that you don’t have
any control over—you can create a shortcut to the program and
mark the shortcut as requiring elevation.
To do this, you set the SLDF_RUNAS_USER
flag in the
shortcut attributes.
Here’s a skeleton program that sets the flag on the shortcut
whose path is passed on the command line.
For expository purposes, I’ve skimped on the error reporting,
and just to shake things up, I’ve used ATL smart pointers.
#include <windows.h> #include <shlobj.h> #include <atlbase.h> void MarkShortcutRunAs(LPCWSTR pszShortcut) { CComPtr<IPersistFile> sppf; if (FAILED(sppf.CoCreateInstance(CLSID_ShellLink))) return; if (FAILED(sppf->Load(pszShortcut, STGM_READWRITE))) return; CComQIPtr<IShellLinkDataList> spdl(sppf); if (!spdl) return; DWORD dwFlags; if (FAILED(spdl->GetFlags(&dwFlags))) return; dwFlags |= SLDF_RUNAS_USER; if (FAILED(spdl->SetFlags(dwFlags))) return; if (FAILED(sppf->Save(NULL, TRUE))) return; wprintf(L"Succeeded\n"); } int __cdecl wmain(int argc, wchar_t *argv[]) { if (argc == 2 && SUCCEEDED(CoInitialize(NULL))) { MarkShortcutRunAs(argv[1]); CoUninitialize(); } return 0; }
There’s not really much to this program.
It creates a shell link object
(CLSID_ShellLink
) and
asks it to load from the file whose path is given on the command line.
It then uses IShellLinkDataList::GetFlags
and
IShellLinkDataList::SetFlags
to fetch the old flags
and set new flags that include SLDF_RUNAS_USER
.
Once that’s done, it saves the result back out.
The hard part was knowing that the SLDF_RUNAS_USER
flag existed in the first place.
(I fear that most people will read this article and say, “Awesome! My program requires elevation, and this is how I can mark my Start menu shortcut to prompt for elevation. Thanks, Raymond!” These people will have completely ignored the opening paragraph, which explains that that is the wrong thing to do.)
0 comments