很多时候,我们需要程序获得管理员权限,以便进行一些需要更高权限的操作(比如修改Program Files里面的文件、系统操作等)。相信已经有不少人已经知道在项目设置里面要求程序必须以管理员身份启动,但有些功能还是可以在非管理员状态下执行的,我们希望在需要的时候再获取到管理员权限。有时普通用户也无法提供管理员权限,我们要想让程序也能运行,这时该怎么办呢?
我百度了好久,并没有找到什么有用的信息。最后试出来一种解决办法,在这里分享一下。
如果不想看长篇的解释,想直接复制代码片,请看文末。
C++ 获得管理员权限 以管理员身份运行程序
在 Microsoft 官网上查找的结果
在官方文档上,我找到了以下信息:
ShellExecute function (shellapi.h)
Syntax
HINSTANCE ShellExecuteA(
HWND hwnd,
LPCSTR lpOperation,
LPCSTR lpFile,
LPCSTR lpParameters,
LPCSTR lpDirectory,
INT nShowCmd
);
Parameters
hwnd
Type: HWND
A handle to the parent window used for displaying a UI or error messages. This value can be NULL if the operation is not associated with a window.
lpOperation
Type: LPCTSTR
A pointer to a null-terminated string, referred to in this case as a verb, that specifies the action to be performed. The set of available verbs depends on the particular file or folder. Generally, the actions available from an object’s shortcut menu are available verbs. The following verbs are commonly used:
edit
Launches an editor and opens the document for editing. If lpFile is not a document file, the function will fail.
explore
Explores a folder specified by lpFile.
find
Initiates a search beginning in the directory specified by lpDirectory.
open
Opens the item specified by the lpFile parameter. The item can be a file or folder.
Prints the file specified by lpFile. If lpFile is not a document file, the function fails.
runas
Launches an application as Administrator. User Account Control (UAC) will prompt the user for consent to run the application elevated or enter the credentials of an administrator account used to run the application.
NULL
The default verb is used, if available. If not, the “open” verb is used. If neither verb is available, the system uses the first verb listed in the registry.
lpParameters
Type: LPCTSTR
If lpFile specifies an executable file, this parameter is a pointer to a null-terminated string that specifies the parameters to be passed to the application. The format of this string is determined by the verb that is to be invoked. If lpFile specifies a document file, lpParameters should be NULL.
lpDirectory
Type: LPCTSTR
A pointer to a null-terminated string that specifies the default (working) directory for the action. If this value is NULL, the current working directory is used. If a relative path is provided at lpFile, do not use a relative path for lpDirectory.
nShowCmd
Type: INT
The flags that specify how an application is to be displayed when it is opened. If lpFile specifies a document file, the flag is simply passed to the associated application. It is up to the application to decide how to handle it. These values are defined in Winuser.h.
SW_HIDE (0)
Hides the window and activates another window.
SW_MAXIMIZE (3)
Maximizes the specified window.
SW_MINIMIZE (6)
Minimizes the specified window and activates the next top-level window in the z-order.
SW_RESTORE (9)
Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW (5)
Activates the window and displays it in its current size and position.
SW_SHOWDEFAULT (10)
Sets the show state based on the SW_ flag specified in the STARTUPINFO structure passed to the CreateProcess function by the program that started the application. An application should call ShowWindow with this flag to set the initial show state of its main window.
SW_SHOWMAXIMIZED (3)
Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED (2)
Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE (7)
Displays the window as a minimized window. The active window remains active.
SW_SHOWNA (8)
Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE (4)
Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL (1)
Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
Return value
Type: HINSTANCE
If the function succeeds, it returns a value greater than 32. If the function fails, it returns an error value that indicates the cause of the failure. The return value is cast as an HINSTANCE for backward compatibility with 16-bit Windows applications. It is not a true HINSTANCE, however. It can be cast only to an int and compared to either 32 or the following error codes below.
(表略,想看详细信息请点击这里)
简单解释
注意:ShellExecuteA
中的字母A是为了区分不同的系统,调用时应使用ShellExecute
ShellExecute
包含6个参数。
第一个参数是HWND
类型,意为创建程序的窗口句柄。具体怎么用我没太明白,我只需传入NULL
即可,如果有谁了解了这一参数的功能欢迎留言。
第二个函数是LPCSTR
类型,无需研究怎么传入,只需用双引号或者TCHAR
类型的数组即可。这个参数可以是"edit"
"explore"
"open"
"print"
"runas"
NULL
,分别可以打开编辑器、在文件资源管理器中查看、打开、屏幕输出和 以管理员身份运行 。
第三个参数是文件路径。同前一个参数,有两种传入方式。见举例:
/* 变量传入参数 */
TCHAR Path[MAX_PATH]; //定义变量,长度为MAX_PATH(一般是260)
ZeroMemory(Path, MAX_PATH); //变量初始化,第二个参数是变量的长度
strcpy(Path, "文件路径"); //将文件路径存进变量
//这里不一定必须用strcpy,可以scanf,第二个参数也可以是另一个变量
ShellExecute(hwnd, lpOperation, Path, lpParameters, lpDictory, nShowCmd);
/* 字符串传入 */
ShellExecute(hwnd, lpOperation, "path", lpParameters, lpDictory, nShowCmd);
第四个参数是运行时的参数,传入方法同上
第五个参数是运行时环境目录
第六个参数是窗口属性(如最大化、最小化等)
返回值有多种错误,这里不一一列举。只要此值大于32,即表示执行成功。举例:
HINSTANCE res;
res = ShellExecute(hwnd, lpOperation, lpFile, lpParameters, lpDictory, nShowCmd);
if((int)res > 32)
{
printf("Succeeded\n");
}
else
{
printf("Failed\nError code : %d\n", (int)res);
}
以管理员身份运行程序
注意:本程序测试时使用DEV C++ 5.11,使用VS时应在字符串前加上L(如L"runas"
)
#include <windows.h>
#include <cstring>
int RunAsAdmin(LPCSTR Path, LPCSTR Param, LPCSTR Dir, int Showcmd)
{
HINSTANCE res;
res = ShellExecute(NULL, "runas", Path, Param, Dir, Showcmd);
return (int)res;
}
使用时直接调用RunAsAdmin
函数即可。
四个参数的含义分别为文件路径、运行时参数、环境目录和显示方式
可以传入TCHAR
类型数组,也可以直接使用双引号字符串传入。中间两个参数可以传入NULL
。
这里我附上一段判断是否有管理员权限的代码,这次百度的结果还算靠谱,亲测有效。
bool IsProcessRunAsAdmin()
{
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
BOOL b = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if(b)
{
CheckTokenMembership(NULL, AdministratorsGroup, &b);
FreeSid(AdministratorsGroup);
}
return b == TRUE;
}
看见这个,我又强化了一下前面获取管理员的代码,如下:
bool IsProcessRunAsAdmin()
{
SID_IDENTIFIER_AUTHORITY NtAuthority = SECURITY_NT_AUTHORITY;
PSID AdministratorsGroup;
BOOL b = AllocateAndInitializeSid(
&NtAuthority,
2,
SECURITY_BUILTIN_DOMAIN_RID,
DOMAIN_ALIAS_RID_ADMINS,
0, 0, 0, 0, 0, 0,
&AdministratorsGroup);
if(b)
{
CheckTokenMembership(NULL, AdministratorsGroup, &b);
FreeSid(AdministratorsGroup);
}
return b == TRUE;
}
short GetAdmin(LPCSTR Param, int Showcmd)
{
if (IsProcessRunAsAdmin())
return 0;
TCHAR Path[MAX_PATH];
ZeroMemory(Path, MAX_PATH);
::GetModuleFileName(NULL, Path, MAX_PATH); //获取程序路径
HINSTANCE res;
res = ShellExecute(NULL, "runas", Path, Param, NULL, Showcmd);
if((int)res > 32)
return 1;
else
return 0;
}
使用时调用GetAdmin
,一个参数是程序运行时的参数,另一个是启动窗口的状态。这个函数会先判断程序是否有管理员权限,如果没有就尝试获取,获取成功就会返回1(表示又启动了一个有管理员权限的程序,并非当前程序获得了管理员权限,这个不可能做到),获取失败返回0,本来已有管理员权限则返回2。