RegQueryValueEx,需要一些帮助

RegQueryValueEx, need some assistance

本文关键字:帮助 RegQueryValueEx      更新时间:2023-10-16

编码方面的菜鸟,任何建议都值得赞赏。

这就是我要做的:

1) 在 HKLM 中打开运行键

2)阅读我制作的名为"测试"的REG_SZ。

3) 读取"测试"的数据

4)如果找到"此数据",则删除密钥。

5) 关闭密钥。

我做错了什么?

#include <iostream>
#include <Windows.h>

using namespace std;

int main() {
char value[1024];
DWORD value_length = 1024;
DWORD keytype = REG_SZ;
HKEY hk;
LONG result;
LONG result2;
char response;
cout << "Would you like to scan? (Y) or (N)";
cin >> response;
if (response == 'Y')
{
    result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, "Software\Microsoft\Windows\CurrentVersion\Run", 0, KEY_ALL_ACCESS | KEY_WOW64_64KEY, &hk);
        if ( result == ERROR_SUCCESS) {
            result2 = RegQueryValueEx(hk, ("Test"), NULL, &keytype, (LPBYTE)&value, &value_length);
            if (result2 == ERROR_ACCESS_DENIED) {
                cout << "Access Denied." << endl;
                RegCloseKey(hk);
                system("pause");
            }
            else if (result2 == ERROR_MORE_DATA) {
                cout << "lpData buffer is too small to receive the data." << endl;
                RegCloseKey(hk);
                system("pause");
            }
            else if (result2 == ERROR_FILE_NOT_FOUND) {
                cout << "Value does not exist for LpValueName." << endl;
                RegCloseKey(hk);
                system("pause");
            }
            else if (result2 == ERROR_SUCCESS) { //If the function succeeds, the return value is ERROR_SUCCESS.
                cout << "The value read from the registry is: " << value << endl;
                RegCloseKey(hk);
                system("pause");
            }
        }
        else if (result == ERROR_FILE_NOT_FOUND)
        {
            cout << "Key not found." << endl;
            system("pause");
        }
    }
    else if (response == 'N')
    {
        return 0;
        system("pause");
    }
}

检查 RegOpenKeyEx 返回的值的逻辑是相反的。仅当返回ERROR_SUCCESS时继续。

if (RegOpenKeyEx(...) == ERROR_SUCCESS)
    .... // go ahead

您没有检查 RegQueryValueEx 的返回值中的错误。它可能失败了。

它可能失败了,因为您没有考虑注册表重定向程序。您正在尝试从注册表的 64 位视图中读取,但您有一个 32 位进程,重定向器意味着您看到 32 位视图。将 KEY_WOW64_64KEY 标志传递给 RegOpenKeyEx 以从 64 位视图读取。

请注意,从注册表 API 函数返回的字符串可能不会以 null 结尾。使用 value_length 中返回的值显式添加 null 终止符。

当您获取读取排序键的代码时,您要将其删除。由于它处于HKLM因此您的进程必须以管理员权限运行。您必须使用具有足够权限的访问标志来删除,换句话说,该标志比KEY_READ更强大。

顺便说一句,由于您选择始终使用 ANSI API,因此使用 TEXT 宏具有误导性。就个人而言,我会选择Unicode API。