日期:2014-05-18 浏览次数:21020 次
C#让程序自动以管理员身份运行
UAC来控制程序访问
?
工具:VS 2008
?
第一步,
????? 新建一个项目(winform)
?
第二步,
????? 在新建项目中,新建项 应用程序清单文件(app.manifest)
?
第三步,
??????打开?app.manifest 文件
????????? 修改 <requestedExecutionLevel level="asInvoker" uiAccess="false" />
????????? 修改为 <requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
????????? 重新编译 打开 debug目录 就可以看到图标右下角有个小盾牌的标识。
如下代码:
<?xml version="1.0" encoding="utf-8"?> <asmv1:assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv1="urn:schemas-microsoft-com:asm.v1" xmlns:asmv2="urn:schemas-microsoft-com:asm.v2" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <assemblyIdentity version="1.0.0.0" name="MyApplication.app"/> <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2"> <security> <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3"> <!-- UAC 清单选项 如果希望更改 Windows 用户帐户控制级别,请用以下节点之一替换 requestedExecutionLevel 节点。 <requestedExecutionLevel level="asInvoker" uiAccess="false" /> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> <requestedExecutionLevel level="highestAvailable" uiAccess="false" /> 如果您希望利用文件和注册表虚拟化提供 向后兼容性,请删除 requestedExecutionLevel 节点。 --> <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> </requestedPrivileges> </security> </trustInfo> </asmv1:assembly>
?
第四步,
????? 程序中判断是否以管理员身份运行
代码如下:
/// <summary> /// 当前是否是管理员身份运行 /// </summary> /// <returns></returns> public static bool IsAdministrator() { try { WindowsIdentity identity = WindowsIdentity.GetCurrent(); WindowsPrincipal principal = new WindowsPrincipal(identity); return principal.IsInRole(WindowsBuiltInRole.Administrator); } catch { return true; } }
?
?
其他:
C# 修改IP地址
static void SetNetworkAdapter() { ManagementBaseObject inPar = null; ManagementBaseObject outPar = null; ManagementClass mc = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc = mc.GetInstances(); foreach (ManagementObject mo in moc) { if (!(bool)mo["IPEnabled"]) continue; //设置ip地址和子网掩码 inPar = mo.GetMethodParameters("EnableStatic"); inPar["IPAddress"] = new string[] { "10.22.21.111", "192.168.1.9" }; inPar["SubnetMask"] = new string[] { "255.255.255.0", "255.255.255.0" }; outPar = mo.InvokeMethod("EnableStatic", inPar, null); //设置网关地址 inPar = mo.GetMethodParameters("SetGateways"); inPar["DefaultIPGateway"] = new string[] { "10.22.21.1", "192.168.10.1" }; outPar = mo.InvokeMethod("SetGateways", inPar, null); //设置DNS inPar = mo.GetMethodParameters("SetDNSServerSearchOrder"); inPar["DNSServerSearchOrder"] = new string[] { "179.32.42.4", "179.32.42.5" }; outPar = mo.InvokeMethod("SetDNSServerSearchOrder", inPar, null); break; } }
??
?
?
?
?
?
?
?
?
?
?
?