Shield Button

 Posted by  Programming  Add comments  Tagged with:
Mar 062012
 

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 24×24 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 16×16, 24×24 and 32×32. 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.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>