using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Security.Principal; using System.Diagnostics;namespace UACApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); GetAndDisplayRights(); } private void GetAndDisplayRights() { WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent()); bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); lblRights.Text = hasAdministrativeRight ? "Running with full rights" : "Running with limited rights"; } private void btnElevate_Click(object sender, EventArgs e)//提升本程序权限重新运行 { RunElevated(Application.ExecutablePath); //Close this instance because we have an elevated instance this.Close(); } private void btnNotepad_Click(object sender, EventArgs e) //提升其他程序权限运行 { //Must run with limited privileges in order to see the UAC window RunElevated("notepad.exe"); } private void RunElevated(string fileName) { ProcessStartInfo processInfo = new ProcessStartInfo(); processInfo.Verb = "runas"; processInfo.FileName = fileName; try { Process.Start(processInfo); } catch (Win32Exception) { //Do nothing. Probably the user canceled the UAC window } } } }
Manifest嵌入
http://topic.csdn.net/u/20091202/11/d0de6a0b-1f14-45ff-a5dd-3d31f93bd29b.html
可以到网上搜索一下这个manifest
高版本的vs可以在linker->manifest里面找到一个默认为invoke的 改成requestAdministrator(以上可能有拼写错误)
引用他人的回复。。
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Security.Principal;
using System.Diagnostics;namespace UACApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GetAndDisplayRights();
} private void GetAndDisplayRights()
{
WindowsPrincipal pricipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());
bool hasAdministrativeRight = pricipal.IsInRole(WindowsBuiltInRole.Administrator); lblRights.Text = hasAdministrativeRight ? "Running with full rights" : "Running with limited rights";
} private void btnElevate_Click(object sender, EventArgs e)//提升本程序权限重新运行
{
RunElevated(Application.ExecutablePath);
//Close this instance because we have an elevated instance
this.Close();
} private void btnNotepad_Click(object sender, EventArgs e) //提升其他程序权限运行
{
//Must run with limited privileges in order to see the UAC window
RunElevated("notepad.exe");
} private void RunElevated(string fileName)
{
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.Verb = "runas";
processInfo.FileName = fileName;
try
{
Process.Start(processInfo);
}
catch (Win32Exception)
{
//Do nothing. Probably the user canceled the UAC window
}
}
}
}