给button添加UAC的小盾牌图标
Sample Code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
RestartElevated();
}
static internal bool IsAdmin()
{
WindowsIdentity id = WindowsIdentity.GetCurrent();
WindowsPrincipal p = new WindowsPrincipal(id);
return p.IsInRole(WindowsBuiltInRole.Administrator);
}
static internal void AddShieldToButton(Button b)
{
b.FlatStyle = FlatStyle.System;
SendMessage(b.Handle, BCM_SETSHIELD, 0, 0xFFFFFFFF);
}
[DllImport("user32")]
public static extern UInt32 SendMessage
(IntPtr hWnd, UInt32 msg, UInt32 wParam, UInt32 lParam);
internal const int BCM_FIRST = 0x1600; //Normal button
internal const int BCM_SETSHIELD = (BCM_FIRST + 0x000C); //Elevated button
internal static void RestartElevated()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = @"d:\";
startInfo.FileName = "ConsoleApplication4.exe";
startInfo.Verb = "runas";
try
{
Process p = Process.Start(startInfo);
}
catch (System.ComponentModel.Win32Exception ex)
{
return;
}
Application.Exit();
}
private void Form1_Load(object sender, EventArgs e)
{
if (!IsAdmin())
{
this.Text += " (Standard)"; //Unnecessary
AddShieldToButton(this.button1); //Important
}
}
}
浙公网安备 33010602011771号