马上加入IBC程序猿 各种源码随意下,各种教程随便看! 注册 每日签到 加入编程讨论群

C#教程 ASP.NET教程 C#视频教程程序源码享受不尽 C#技术求助 ASP.NET技术求助

【源码下载】 社群合作 申请版主 程序开发 【远程协助】 每天乐一乐 每日签到 【承接外包项目】 面试-葵花宝典下载

官方一群:

官方二群:

C#编写以管理员身份运行的程序[转载]

[复制链接]
查看2919 | 回复0 | 2015-3-3 09:21:03 | 显示全部楼层 |阅读模式
转载博客园,C#实现使用管理员才可运行的软件。

[C#] 纯文本查看 复制代码
using System;
 
using System.Collections.Generic;
 
using System.Linq;
 
using System.Windows.Forms;
 
 
 
namespace MyWebBrowser
 
{
 
    static class Program
 
    {
 
        /// <summary>
 
        /// 应用程序的主入口点。
 
        /// </summary>
 
        [STAThread]
 
        static void Main()
 
        {
 
            //获得当前登录的Windows用户标示
 
            System.Security.Principal.WindowsIdentity identity = System.Security.Principal.WindowsIdentity.GetCurrent();
 
            System.Security.Principal.WindowsPrincipal principal = new System.Security.Principal.WindowsPrincipal(identity);
 
            //判断当前登录用户是否为管理员
 
            if (principal.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator))
 
            {
 
                //如果是管理员,则直接运行
 
                Application.EnableVisualStyles();
 
                Application.SetCompatibleTextRenderingDefault(false);
 
                Application.Run(new Form1());
 
            }
 
            else
 
            {
 
                //创建启动对象
 
                System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
 
                //设置运行文件
 
                startInfo.FileName = System.Windows.Forms.Application.ExecutablePath;
 
                //设置启动动作,确保以管理员身份运行
 
                startInfo.Verb = "runas";
 
                //如果不是管理员,则启动UAC
 
                System.Diagnostics.Process.Start(startInfo);
 
                //退出
 
                System.Windows.Forms.Application.Exit();
 
            }
 
        }
 
    }
 
}

C#论坛 www.ibcibc.com IBC编程社区
C#
C#论坛
IBC编程社区
*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则