前言
自 Windows Vista 開始,系統(tǒng)就增加了UAC(用戶賬戶控制) 的安全機制,當(dāng) UAC 被打開,我們即使以管理員權(quán)限登錄,應(yīng)用程序默認(rèn)情況下也無法對系統(tǒng)目錄、系統(tǒng)注冊表等進行操作,從而提升了系統(tǒng)的安全性。但對我們開發(fā)的應(yīng)用程序來說,程序如何以管理員的方式運行,則需開發(fā)者考慮。本文介紹了 C# 程序如何實現(xiàn)用戶以管理員權(quán)限運行。
實現(xiàn)
1、修改應(yīng)程序文件的屬性
在安裝好的應(yīng)用程序目錄中,右擊程序文件,選擇屬性,然后在彈出的屬性界面中找到兼容性標(biāo)簽頁,勾選以管理員身份運行此程序。其實這種方式并不是開發(fā)者實現(xiàn)的,只是用戶根據(jù)指引調(diào)整實現(xiàn)。這為用戶者帶來了不少的麻煩,操作起來也不友好。
2、通過配置應(yīng)用程序清單文件
在 C# 的項目上,可通過右擊項目,選擇添加,在新項中選擇應(yīng)用程序清單文件(僅限Windows) 添加文件到項目中。打開文件,找到與UAC相關(guān)設(shè)置項。
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
修改為:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
修改文件后,將清單文件添加到項目的資源中,右擊項目-->屬性-->資源-->添加資源文件(選擇app.manifest)。重新生成項目后,打開應(yīng)用程序時就會提示需要以管理員權(quán)限運行。如下圖:

注意:通過配置上面方式后,我們應(yīng)該使用管理員身份運行 Microsoft Visual Studio。否則提示下圖:

3、通過在程序入口編寫代碼
在應(yīng)用程序入口文件 Program.cs 添加相關(guān)代碼。主要使用Process.Start 方式啟動應(yīng)用程,使用此方式 ,運行程序時,也會提示以管理員身份運行,需要用戶點擊提示才以啟動程序。
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Fountain.WinForms.UACDemo
{
internal static class Program
{
internal static ApplicationContext context = null;
/// <summary>
/// 應(yīng)用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
if (IsRunAsAdmin())
{
// 是管理員角色,管理員權(quán)限運行
context = new ApplicationContext(new FormMain());
Application.Run(context);
}
else
{
// 使用 ProcessStartInfo 以管理員方式啟動
RunAsAdmin();
//退出
Application.Exit();
}
}
/// <summary>
/// 使用 ProcessStartInfo 以管理員方式啟動
/// </summary>
public static void RunAsAdmin()
{
ProcessStartInfo startInfo = new ProcessStartInfo();
//設(shè)置以管理員方式啟動標(biāo)記
startInfo.Verb = "runas";
//使用shell啟動進程
startInfo.UseShellExecute = true;
startInfo.FileName = Process.GetCurrentProcess().MainModule.FileName;
Process.Start(startInfo);
}
/// <summary>
/// 判斷當(dāng)前角色,是否為管理員權(quán)限運行
/// </summary>
/// <returns></returns>
public static bool IsRunAsAdmin()
{
// 獲取當(dāng)前的windows 用戶
WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent();
// 檢查 獲取當(dāng)前的windows 用戶 的 Windows 組成員身份。
WindowsPrincipal windows = new WindowsPrincipal(windowsIdentity);
// 判斷當(dāng)前用戶是否是管理員
if (windows.IsInRole(WindowsBuiltInRole.Administrator))
{
return true;
}
return false;
}
}
}
小結(jié)
上面三種方式,除第一種方式,不是在編寫應(yīng)用程序時指定以管理員權(quán)限方式啟動的實現(xiàn),但都能實現(xiàn)管理員權(quán)限運行應(yīng)用程序的目的。在使用代碼時,我們還可增加判斷當(dāng)前是否開啟UAC、判斷UAC管理員提升權(quán)限提示行為等來確認(rèn)啟動管理員權(quán)限運行的提前條件。希望這些內(nèi)容對您有所幫助,如有不到之處,請多多包涵。如果你覺得還有其它例子歡迎留言。
該文章在 2024/10/22 12:10:40 編輯過