【发布时间】:2016-03-17 03:50:49
【问题描述】:
编码新手,欢迎提出任何建议。
这就是我想要做的:
1) 在 HKLM 中打开运行键
2) 阅读我制作的名为“Test”的 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");
}
}
【问题讨论】:
-
你试过
cout << value << '\n';看看它打印了什么吗? -
到底是什么问题?你已经知道如何读取数据,你已经在做。数据在您的
value[]数组中。RegQueryValueEx()的返回值(您将忽略)将告诉您该值是否存在于打开的密钥中,value_length将告诉您读取了多少字节。然后你只需要扫描value[]的内容,比如strncmp(),strstr()等,看你的需要。如果您找到匹配项,请致电RegDeleteValue()。 -
在不相关的注释中,
ERROR_SUCCESS是一个误导性名称! -
您正在测试
RegOpenKeyEx是否失败 (!= ERROR_SUCCESS),这意味着如果成功,您将不会从注册表中读取值并且value未初始化。 -
更新问题中的代码,不要将其粘贴到评论中。如果它“失败”,请解释如何它失败了。