注意事项
注意:①64位操作系统注册表会重定向,RegOpenKeyEx第4个参数得加上KEY_WOW64_64KEY;②RegOpenKeyEx遍历子项时注意第2和第4参数,参考图:
③RegQueryValueEx同样得注意第6参数
完整代码
std::unordered_map<std::string, std::string> GetAllAutoCADInstallPaths()
{
// 定义结果映射,键为版本号,值为安装路径
std::unordered_map<std::string, std::string> installPaths;
// 打开 AutoCAD 注册表项
HKEY hKey;
LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Autodesk\\AutoCAD", 0, KEY_READ | KEY_WOW64_64KEY, &hKey);
if (lResult != ERROR_SUCCESS) return installPaths;
DWORD dwIndex = 0;
TCHAR szSubKeyName[MAX_PATH];
DWORD dwSize = sizeof(szSubKeyName);
vector<string> vecSubKey;
// 遍历子项
while ((lResult = RegEnumKeyEx(hKey, dwIndex, szSubKeyName, &dwSize, NULL, NULL, NULL, NULL)) == ERROR_SUCCESS)
{
vecSubKey.emplace_back(string("SOFTWARE\\Autodesk\\AutoCAD\\")+szSubKeyName);
++dwIndex;
dwSize = MAX_PATH;
}
vector<string> vecSubSubKey;
for (auto &strKey : vecSubKey)
{
HKEY hSubKey;
LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, strKey.c_str(), 0, KEY_READ | KEY_WOW64_64KEY, &hSubKey);
if (lResult != ERROR_SUCCESS) return installPaths;
dwIndex = 0;
while ((lResult = RegEnumKeyEx(hSubKey, dwIndex, szSubKeyName, &dwSize, NULL, NULL, NULL, NULL)) == ERROR_SUCCESS)
{
vecSubSubKey.emplace_back(strKey + "\\" + szSubKeyName);
++dwIndex;
dwSize = MAX_PATH;
}
// 关闭键
RegCloseKey(hSubKey);
}
for(auto &strKey : vecSubSubKey)
{
HKEY hSubKey;
LONG lResult = RegOpenKeyEx(HKEY_LOCAL_MACHINE, strKey.c_str(), 0, KEY_READ| KEY_WOW64_64KEY, &hSubKey);
if (lResult != ERROR_SUCCESS) return installPaths;
char installPath[MAX_PATH];
char name[MAX_PATH];
DWORD size = MAX_PATH;
if(RegQueryValueEx(hSubKey, "Location", NULL, NULL, reinterpret_cast<LPBYTE>(installPath), &size) == ERROR_SUCCESS)
{
size = MAX_PATH;
RegQueryValueEx(hSubKey, "ProductName", NULL, NULL, reinterpret_cast<LPBYTE>(name), &size);
installPaths[string(name)] = string(installPath);;
}
// 关闭键
RegCloseKey(hSubKey);
}
// 关闭键
RegCloseKey(hKey);
return installPaths;
}