97 lines
2.7 KiB
C++
97 lines
2.7 KiB
C++
#include <windows.h>
|
|
#include <shellapi.h>
|
|
#include <sddl.h>
|
|
#include <tchar.h>
|
|
#include <iostream>
|
|
#include<string>
|
|
|
|
using namespace std;
|
|
|
|
bool IsRunAsAdmin() {
|
|
BOOL isAdmin = FALSE;
|
|
PSID adminGroup = NULL;
|
|
|
|
// SID for Administrators group
|
|
SID_IDENTIFIER_AUTHORITY ntAuthority = SECURITY_NT_AUTHORITY;
|
|
if (AllocateAndInitializeSid(&ntAuthority, 2, SECURITY_BUILTIN_DOMAIN_RID,
|
|
DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &adminGroup)) {
|
|
if (!CheckTokenMembership(NULL, adminGroup, &isAdmin)) {
|
|
isAdmin = FALSE;
|
|
}
|
|
FreeSid(adminGroup);
|
|
}
|
|
|
|
return isAdmin == TRUE;
|
|
}
|
|
|
|
void RunAsAdmin() {
|
|
TCHAR szPath[MAX_PATH];
|
|
if (!GetModuleFileName(NULL, szPath, ARRAYSIZE(szPath))) {
|
|
cerr << "Failed to get module file name." << endl;
|
|
return;
|
|
}
|
|
|
|
SHELLEXECUTEINFO sei = { sizeof(sei) };
|
|
sei.lpVerb = TEXT("runas");
|
|
sei.lpFile = szPath;
|
|
sei.hwnd = NULL;
|
|
sei.nShow = SW_NORMAL;
|
|
|
|
if (!ShellExecuteEx(&sei)) {
|
|
DWORD dwError = GetLastError();
|
|
if (dwError == ERROR_CANCELLED) {
|
|
cerr << "The user refused to allow elevation." << endl;
|
|
} else {
|
|
cerr << "ShellExecuteEx failed with error code " << dwError << endl;
|
|
}
|
|
}
|
|
}
|
|
|
|
int _tmain() {
|
|
if (!IsRunAsAdmin()) {
|
|
cout << "Program is not running with administrator privileges. Attempting to restart as administrator..." << endl;
|
|
RunAsAdmin();
|
|
return 0; // Exit the current instance
|
|
}
|
|
|
|
// Your code that requires admin privileges goes here
|
|
cout << "Program is running with administrator privileges." << endl;
|
|
|
|
// Example of code that requires admin privileges
|
|
// You can add any code here that needs admin rights
|
|
// 例如:修改系统设置、访问受限文件等
|
|
extern string choose;
|
|
string choose = "";
|
|
|
|
cout <<"C++ command v1.0"<<endl;
|
|
cout <<"https://github.com/dengrb1/"<<endl;
|
|
|
|
while (choose!="exit")
|
|
{
|
|
cin >>choose;
|
|
if (choose=="list")
|
|
{
|
|
system("dir");
|
|
}else if (choose=="help")
|
|
{
|
|
cout <<"------------------------------------"<<endl;
|
|
cout <<"C++ command帮助菜单"<<endl;
|
|
cout <<"注意!本程序区分大小写!"<<endl;
|
|
cout <<"list--当前运行环境目录"<<endl;
|
|
cout <<"help--帮助菜单"<<endl;
|
|
cout <<"cd--加载文件夹"<<endl;
|
|
cout <<"------------------------------------"<<endl;
|
|
choose = Unknown;
|
|
}else{
|
|
cout <<choose<<"没有这个指令!"<<endl;
|
|
choose = Unknown;
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// Prevent closing immediately to observe behavior
|
|
|
|
return 0;
|
|
}
|