WPF 检测管理员权限

时间:2023-12-14 22:14:14
      // 检查是否是管理员身份
private static bool CheckAdministrator()
{
WindowsIdentity wi = null;
try
{
wi = WindowsIdentity.GetCurrent();
if (wi == null) throw new Exception("未将对象仅用到对象的实例!");
var wp = new WindowsPrincipal(wi);
var runAsAdmin = wp.IsInRole(WindowsBuiltInRole.Administrator);
if (runAsAdmin) return true;
var processInfo = new ProcessStartInfo(Assembly.GetExecutingAssembly().CodeBase)
{
UseShellExecute = true,
Verb = "runas"
}; Process.Start(processInfo);
return false;
}
catch
{
Console.WriteLine("失败!");
return true;
}
finally
{
if (wi != null)
wi.Dispose();
}
}

应用

    /// <summary>
/// 应用程序的主入口点。
/// </summary>
[STAThread]
static void Main()
{
if (CheckAdministrator())
{
int count = ;
Process[] myProcess = Process.GetProcesses();
foreach (Process _Process in myProcess)
{
if (_Process.ProcessName == Process.GetCurrentProcess().ProcessName)
{
count++;
}
}
if (count > )
{
MessageBox.Show("程序已启动,请勿重复打开!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
} } }