Windows Vista introduced us to UAC. One cornerstone for developers was displaying shield next to a button that requires elevation. And it is shame that most application still don’t draw it.
Code is really simple:
var hIcon = NativeMethods.LoadImageW(IntPtr.Zero, NativeMethods.IDI_SHIELD, NativeMethods.IMAGE_ICON, 24, 24, NativeMethods.LR_DEFAULTCOLOR);
if (!hIcon.Equals(System.IntPtr.Zero)) {
var icon = System.Drawing.Icon.FromHandle(hIcon);
if (icon != null) {
this.TextImageRelation = TextImageRelation.ImageBeforeText;
this.Image = icon.ToBitmap();
}
}
As you can see, all things are done in first line. Using Interop we request for a system’s shield icon, sized 24x24 pixels in default color. All other lines are there just to be sure that something was loaded and you are not crashing if not (e.g. if you are running XP).
Notice that one could use SystemInformation.SmallIcon
to determine “proper” icon size. Unfortunately that will not have nice result for icon sizes that are not 16x16, 24x24 and 32x32. You could always do some fancy smoothing but at such small icon sizes I think it is best to go for something that is of native size.
As example I took liberty to make Button control with UAC shield. Full source is available for download.