方法一:关闭程序重新请求打开

static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false); /**
* 当前用户是管理员的时候,直接启动应用程序
* 如果不是管理员,则使用启动对象启动程序,以确保使用管理员身份运行
*/
//获得当前登录的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.Run(new Form1());
}
else
{
//创建启动对象
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.UseShellExecute = true;
startInfo.WorkingDirectory = Environment.CurrentDirectory;
startInfo.FileName = Application.ExecutablePath;
//设置启动动作,确保以管理员身份运行
startInfo.Verb = "runas";
try
{
System.Diagnostics.Process.Start(startInfo);
}
catch
{
return;
}
//退出
Application.Exit();
}
}
}

方法二:修改manifest

在 项目 上 添加新项 选择“应用程序清单文件” 然后单击 添加 按钮

添加后,默认打开app.manifest文件,将:

<requestedExecutionLevel  level="asInvoker" uiAccess="false" />

修改为:

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

然后打开 项目属性 ,将 应用程序 标签页中的 资源 中的 清单 修改为新建的 app.manifest。

重新生成项目,再次打开程序时就会提示 需要以管理员权限运行。

最新文章

  1. Ubuntu环境下安装TinyOS系统
  2. java转义字符(转载)
  3. Wpf 数据绑定之BindingBase.StringFormat
  4. sqlserver提高篇
  5. FFMPEG结构体分析:AVPacket
  6. There Are Now 3 Apache Spark APIs. Here’s How to Choose the Right One
  7. [原创]K8_Delphi源码免杀系列教程
  8. JSP动态网页
  9. [原创] MSP430G2系列图形化编程相关资料
  10. cp自动创建层级结构的例子
  11. framework4.0 IIS7下urlrewriter设置问题
  12. .net core2.0 codefirst 创建数据库的问题!
  13. 如何安装windows7
  14. nginx1.9+新增tcp/udp代理stream
  15. 用Javascript轻松制作一套简单的抽奖系统
  16. SQL Server笔记——sql语句创建数据库
  17. 创建第一个maven项目的那些坑
  18. 【bzoj4898】[Apio2017]商旅 Floyd+分数规划+Spfa
  19. custom post types 404 Page Error
  20. Make 学习笔记(1)

热门文章

  1. Android Studio导入第三方类库的方法
  2. 本地数据Store。Cookie,Session,Cache的理解。Timer类主要用于定时性、周期性任务 的触发。刷新Store,Panel
  3. word20161222
  4. ovirt配置为cas登录
  5. nginx windows负载均衡入门
  6. 关于SimpleAdapter和ListView结合使用,实现列表视图的笔记
  7. 设计模式--适配器模式Adapter(结构型)
  8. 解决NetBeans运行web项目时出现的&ldquo;未能正确设置java DB&rdquo;问题
  9. Python3实现火车票查询工具
  10. Windows 网络编程