Skip to content

Instantly share code, notes, and snippets.

@iobzo
Forked from kingsamchen/self_elevation.cpp
Last active December 23, 2015 01:37
Show Gist options
  • Save iobzo/a0e1359163590684dce5 to your computer and use it in GitHub Desktop.
Save iobzo/a0e1359163590684dce5 to your computer and use it in GitHub Desktop.
class ScopeGuard
{
public:
ScopeGuard( std::function< void() > onScopeExit ) { m_onScopeExit = onScopeExit; }
~ScopeGuard() { m_onScopeExit(); }
private:
std::function< void() > m_onScopeExit;
};
#define SCOPEGUARD_LINENAME_CAT(name, line) name##line
#define SCOPEGUARD_LINENAME(name, line) SCOPEGUARD_LINENAME_CAT(name, line)
#define OnScopeExit( callback ) ScopeGuard SCOPEGUARD_LINENAME( myScopeGuard, __LINE__ ) ( [&] { callback; } );
BOOL IsProcessElevated()
{
BOOL isElevated = FALSE;
HANDLE hToken = NULL;
DWORD errCode = 0;
BOOL ret = OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken);
errCode = GetLastError();
OnScopeExit(
if (hToken)
{
CloseHandle(hToken);
hToken = NULL;
}
);
if (!ret)
{
throw errCode;
}
TOKEN_ELEVATION elevationInfo;
DWORD retSize = 0;
if (!GetTokenInformation(hToken, TokenElevation, &elevationInfo,
sizeof(elevationInfo), &retSize))
{
errCode = GetLastError();
throw errCode;
}
isElevated = elevationInfo.TokenIsElevated;
return isElevated;
}
void OnCommand(HWND hWnd, int id, HWND hwndCtl, UINT codeNotify)
{
switch (id)
{
case IDC_BTNELEVATION:
BOOL isElevated = IsProcessElevated();
if (isElevated)
{
MessageBox(hWnd, L"Arealdy run at full administrator token",
L"warning", MB_OK | MB_ICONEXCLAMATION);
return;
}
else
{
wchar_t path[MAX_PATH];
if (GetModuleFileName(NULL, path, MAX_PATH))
{
SHELLEXECUTEINFO sei = {sizeof(SHELLEXECUTEINFO)};
sei.lpVerb = L"runas";
sei.lpFile = path;
sei.hwnd = hWnd;
sei.nShow = SW_NORMAL;
if (!ShellExecuteEx(&sei))
{
DWORD errCode = GetLastError();
if (errCode == ERROR_CANCELLED)
{
// cancelled elevation
}
}
else
{
}
}
}
break;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment