Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a menu item with UAC-shield in C++?

Tags:

c++

winapi

I want to create a menu item for an action that will require elevation.

The Windows UI guidelines state that such actions should have the UAC-shield displayed next to them.

How can I do that using plain Windows API and C++?

like image 365
tehlexx Avatar asked Dec 17 '22 19:12

tehlexx


1 Answers

The Windows shell does provide various default icons, among which is also the UAC-shield icon.

Loading the icon

SHSTOCKICONINFO ssii = {};
ssii.cbSize = sizeof(ssii);
SHGetStockIconInfo(SIID_SHIELD, SHGSI_ICON | SHGSI_SMALLICON, &ssii);

This gives you a HICON, however SetMenuItemBitmaps requires a HBITMAP so the HICON needs to be converted:

ICONINFOEX iconInfo = {};
iconInfo.cbSize = sizeof(iconInfo);
GetIconInfoEx(ssii.hIcon, &iconInfo);
auto bitmap = (HBITMAP)CopyImage(iconInfo.hbmColor, IMAGE_BITMAP, 0, 0, LR_CREATEDIBSECTION);

Finally, set the icon:

SetMenuItemBitmaps(hMenu, YOUR_MENU_ITEM_COMMAND, MF_BYCOMMAND, bitmap, bitmap);

Clean-up:

DestroyIcon(ssii.hIcon);

bitmap needs to be destroyed after the menu is destroyed (using DeleteObject(bitmap);), or will be cleaned up when the application shuts down, as described in CopyImage(MSDN) and SetMenuItemBitmaps(MSDN).

like image 190
tehlexx Avatar answered Dec 28 '22 23:12

tehlexx