首页 > 解决方案 > 在 C++ 中递归搜索注册表

问题描述

我的搜索注册表功能有问题。我的目标是输入键名并遍历注册表树,直到找到具有此名称的键。我的函数可以遍历整个树(深度优先),但问题在于搜索 - 我只能成功搜索“第一级”上的键。但是,如果我尝试搜索,例如,HKEY_CURRENT_USER\AppEvents\Schemes,“Schemes”键将被跳过。对于搜索,我使用 found 标志,想法是在设置为 false 时继续搜索。但是 if (!found) { //function code } 和 while (!found) 似乎都对我没有用。我错过了什么以及如何解决它?

我的代码是:

#define BUFF_SIZE 400

void searchKeys(HKEY, string, TCHAR*, bool);

int main()
{
    HKEY rootKey= HKEY_CLASSES_ROOT;
    int keyMenu;
    TCHAR searchedName[BUFF_SIZE];
    bool found = false;


    cout << "Select root key: " << endl;
    cout << "1 - HKEY_CLASSES_ROOT\n2 - HKEY_CURRENT_USER\n3 - HKEY_LOCAL_MACHINE\n4 - HKEY_USERS\n5 - HKEY_CURRENT_CONFIG"<<endl;
    cin >> keyMenu;

    switch (keyMenu) {
    case 1: rootKey = HKEY_CLASSES_ROOT;
        break;
    case 2: rootKey = HKEY_CURRENT_USER;
        break;
    case 3: rootKey = HKEY_LOCAL_MACHINE;
        break;
    case 4: rootKey = HKEY_USERS;
        break;
    case 5: rootKey = HKEY_CURRENT_CONFIG;
        break;
    default: 
        cout << "This root key does not exist" << endl;
        system("PAUSE");
        return 0;
    }


    cout << "Enter key name to search: " << endl;
    cin >> searchedName;
    cout << "\n";

    string subKeyPath = "";

    searchKeys(rootKey, subKeyPath, searchedName, found);

    system("PAUSE");
    return 0;
}

void searchKeys(HKEY rootKey, string subKeyPath, TCHAR* searchedName, bool found) {
    HKEY subKey;
    DWORD subKeyCount, buffSize;
    char subKeyBuff[BUFF_SIZE];
    char result[BUFF_SIZE];

    TCHAR sbNameBuf[BUFF_SIZE];
    const char * subKeyName;
    subKeyName = subKeyPath.c_str();
    copy(subKeyPath.begin(), subKeyPath.end(), sbNameBuf);

    //if (!found) {
    //while (!found) {
        DWORD output = RegOpenKeyEx(rootKey, subKeyName, NULL, KEY_ALL_ACCESS, &subKey); //open specified root catalogue

        if (output != ERROR_SUCCESS) return;

        RegQueryInfoKey(subKey, NULL, NULL, NULL, &subKeyCount, NULL, NULL, NULL, NULL, NULL, NULL, NULL); //get info about root key

        if (!subKeyCount) return;

        for (DWORD i = 0; i < subKeyCount && !found; i++) {
            buffSize = sizeof(subKeyBuff);
            RegEnumKeyEx(subKey, i, subKeyBuff, &buffSize, NULL, NULL, NULL, NULL);

            string keyName = subKeyBuff;

            if (strcmp(subKeyBuff, searchedName) == 0) {
                found = true;
            }
            else {
                cout << subKeyBuff << endl;
            }

            keyName = subKeyPath + subKeyBuff + "\\";
            RegOpenKeyEx(rootKey, subKeyName, NULL, KEY_ALL_ACCESS, &subKey);
            RegQueryInfoKey(subKey, NULL, NULL, NULL, &subKeyCount, NULL, NULL, NULL, NULL, NULL, NULL, NULL); //get subKeyCount

            if (subKeyCount) {
                searchKeys(rootKey, keyName, searchedName, found);
            }

        }
    //}
    //}

}

标签: c++recursionsearchregistry

解决方案


这个问题的解决方案是简单地使 bool found 变量成为全局变量。此外,engf-010 评论对于查看所有键很有用。


推荐阅读