BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Security
.NET 1.1

Creating an Elevated Button Control

When using Microsoft Windows Vista, administrative tasks are restricted by the user account control (UAC) system. Buttons that require elevated permissions are displayed with the command text and a shield icon to indicate that permission will be required.

Displaying the Elevated Icon

To display the shield icon on the button, we need to call the SendMessage function. Of the four parameters, the first two are the most interesting. The first parameter specifies the handle of the window that is to be modified. To obtain the handle, we will create a new HandleRef structure, passing the button control and its Handle property to the structure's constructor.

The second parameter is the message to be sent to the button. This is the BCM_SETSHIELD message. The third and fourth parameters are used to pass message-specific information. In this case they will be passed values of zero and one respectively, each held in an IntPtr structure.

To create the code that calls SendMessage, add the following method to the class:

private void ShowShield()
{
    IntPtr wParam = new IntPtr(0);
    IntPtr lParam = new IntPtr(1);
    SendMessage(new HandleRef(this, Handle), BCM_SETSHIELD, wParam, lParam);
}

Creating the Constructor

The final member to add to the new control's class is its constructor. We will use the constructor to add the shield to the button if the program does not currently have elevated privileges. To create the constructor, add the following code to the ElevatedButton class. Note that the first line of the constructor sets the button's FlatStyle property to "System". This style of button is required to show the elevated icon. If the property is changed, the shield will not be visible.

public ElevatedButton()
{
    FlatStyle = FlatStyle.System;

    if (!IsElevated()) ShowShield();
}

Testing the Control

You can test the ElevatedButton control by compiling the code and adding the control to the Visual Studio toolbox. You can then create a new Windows Forms project and add the control to a form using the toolbox icon. Compile the Windows Forms application in release mode and then run the executable in normal mode and as an administrator to see that the icon appears only when required.

6 April 2009