By now, I’m sure that everyone has seen the little shield image on a button or file:
We all know that it means that you need adminstrator rights, or to log in to an admin account in order to install something or perform some operation that only admins can do. Well recently I’ve been working on an install and on the auto-updating feature of Bitter, so I really wanted the ability to show this so that users immediately knew that it required admin rights. But how do you do this in C#? Well, of course, there’s no simple Button.ShowShield() method or anything as easy as that. You need to import a dll and then call a method with a certain constant. Fun, eh? Anyway, I wrapped all that into a class and thought I’d share. If anyone finds any bugs or improvements let me know. Enjoy!
class ShieldButton : Button
{
[DllImport("user32.dll")]
private static extern IntPtr SendMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
// Define BCM_SETSHIELD locally, declared originally in Commctrl.h
private const uint BCM_SETSHIELD = 0×0000160C;
private bool m_useShield = true;
protected override void OnCreateControl()
{
base.OnCreateControl();
SetShield();
}
private void SetShield()
{
if (m_useShield)
{
// Set button style to the system style, else the shield image won’t show
this.FlatStyle = FlatStyle.System;
// Send the BCM_SETSHIELD message to the button control to show the shield image
SendMessage(new HandleRef(this, this.Handle), BCM_SETSHIELD, new IntPtr(0), new IntPtr(1));
}
else
{
// Send the BCM_SETSHIELD message to the button control to hide the shield image
SendMessage(new HandleRef(this, this.Handle), BCM_SETSHIELD, new IntPtr(0), new IntPtr(0));
// Set button style back to the system style, since we removed the shield image
this.FlatStyle = FlatStyle.Standard;
}
}
public bool Enabled
{
get
{
return base.Enabled;
}
set
{
// need to hide the shield image before disabling, else it won’t disable properly
m_useShield = value;
SetShield();
base.Enabled = value;
}
}
}