#include #include #include #include #include #include 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"<>choose; if (choose=="list") { system("dir"); }else if (choose=="help") { cout <<"------------------------------------"<