详细的具体步骤或操作方法
1一、软件自身运行时的管理员权限申请机制2在开启UAC的时候,在Win7(Windows Server 2008 R2)或者Vista(Windows Server 2008)中执行程序默认是以一种权限较低的方式执行的,但是在这种方式下,我们有些操作会失败(比如修改注册表,监听端口,往系统目录写入文件等),要实现这些操作,就需要我们以管理员权限执行程序了。
3当然,只有在程序上右键,选择“以管理员执行”就可以,不过如何让程序自己自动以管理员权限来运行呢,这就需要Manifest了。
4首先我们来新建个项目(懒得改名字了,就叫WindowsFormsApplication1吧)
5按F5执行下(恩,貌似没有啥问题[空文档,有问题才怪... ])
6然后我们添加Manifest(中文版叫“应用程序清单文件”) 
7下面我们看下Manifest的内容——8内容里的说明够详细了吧,只要把 asInvoker替换成requireAdministrator,我们的程序就会默认要求管理员权限运行了,该下执行试试效果。
恩,窗口弹出来了。 看下程序图标:
大功告成...

9二、下面再说下怎么给程序的按钮上也加上小盾牌图标吧 这我们就需要调用Win32 API了,要调用API么,要先引用命名空间——
using System.Runtime.InteropServices;
然后调用API
[DllImport("user32.dll")] private static extern IntPtr SMessage(HandleRef hWnd, uint Msg, IntPtr wParam, IntPtr lParam);
///////////////////////////////////////////////////////////////////////
///
/// Enables the elevated shield icon on the given button control
///
///
aram name="ThisButton">
/// Button control to enable the elevated shield icon on.
///
///////////////////////////////////////////////////////////////////////
private void EnableElevateIcon_BCM_SETSHIELD(Button ThisButton)
{
// Input validation, validate that ThisControl is not null
if (ThisButton==null)
{
return;
}
// Define BCM_SETSHIELD locally, declared originally in Commctrl.h
uint BCM_SETSHIELD=0x0000160C;
// Set button style to the system style
ThisButton.FlatStyle=FlatStyle.System;
// S the BCM_SETSHIELD message to the button control
SMessage(new HandleRef(ThisButton, ThisButton.Handle), BCM_SETSHIELD, new IntPtr(0), new IntPtr(1));
}
在Form上拖个Button,拖大一点哦,小了图标看不清
然后在Form1_Load里,用API把图标加到Button1上
private void Form1_Load(object ser, EventArgs e)
{
EnableElevateIcon_BCM_SETSHIELD(button1);
}
10最后执行看下效果吧!
恩?盾牌为啥有点不一样呢,上面那个图标是Windows Server 2008或者Vista上的,Win7和Windows Server 2008 R2上应该是下面这样:
有错误的地方欢迎指证喔。
经验内容仅供参考,如果您需解决具体问题(尤其法律、医学等领域),建议您详细咨询相关领域专业人士。
- 评论列表(网友评论仅供网友表达个人看法,并不表明本站同意其观点或证实其描述)
-
