[C#]Enable UAC Shield icons and run as administrator
#region Private Method
private static bool AtLeastVista()
{
return (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6);
}
private static void SetButtonShield(Button btn, bool showShield)
{
if (!AtLeastVista())
return;
btn.FlatStyle = FlatStyle.System;
SendMessage(new HandleRef(btn, btn.Handle), BCM_SETSHIELD, IntPtr.Zero, showShield ? new IntPtr(1) : IntPtr.Zero);
}
#endregion</pre>
public static class ButtonExtension { #region DllImport [DllImport(“shell32.dll”, EntryPoint = “#680”, CharSet = CharSet.Unicode)] private static extern bool IsUserAnAdmin();
[DllImport("user32.dll", CharSet = CharSet.Unicode)]
private static extern IntPtr SendMessage(HandleRef hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);
#endregion
#region Const
const int BCM_SETSHIELD = 0x0000160C;
#endregion
#region Private Method
private static bool AtLeastVista()
{
return (Environment.OSVersion.Platform == PlatformID.Win32NT && Environment.OSVersion.Version.Major >= 6);
}
private static void SetButtonShield(Button btn, bool showShield)
{
if (!AtLeastVista())
return;
btn.FlatStyle = FlatStyle.System;
SendMessage(new HandleRef(btn, btn.Handle), BCM_SETSHIELD, IntPtr.Zero, showShield ? new IntPtr(1) : IntPtr.Zero);
}
private static Form GetWindowForm(Control control)
{
Control parent = control.Parent;
if (parent == null)
return null;
if(parent is Form)
return parent as Form;
return GetWindowForm(parent);
}
#endregion
#region Public Method
public static void EnableShieldIcon(this Button button)
{
SetButtonShield(button, true);
}
public static void EnableRunAsProcess(this Button button)
{
button.Click -= new EventHandler(button_RunAsProcess);
button.Click += new EventHandler(button_RunAsProcess);
}
#endregion
#region Event Process
private static void button_RunAsProcess(object sender, EventArgs e)
{
Button button = sender as Button;
Form form = GetWindowForm(button);
if (form == null)
return;
ProcessStartInfo psi = new ProcessStartInfo
{
Arguments = "-justelevated",
ErrorDialog = true,
ErrorDialogParentHandle = form.Handle,
FileName = Application.ExecutablePath,
Verb = "runas"
};
try
{
Process.Start(psi);
form.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
#endregion
}