Total noob at coding, any advice is appreciated.
This is what I am trying to do:
1) Open the run key in HKLM
2) Read a REG_SZ I have made called "Test".
3) Read the data for "Test"
4) If "this data" found then delete key.
5) Close the key.
What am I doing wrong?
#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");
}
}
The logic of your check on the value returned by RegOpenKeyEx
is reversed. Only proceed if ERROR_SUCCESS
is returned.
if (RegOpenKeyEx(...) == ERROR_SUCCESS)
.... // go ahead
You aren't checking for errors in the return value of RegQueryValueEx
. It is probably failing.
It is probably failing because you aren't accounting for the registry redirector. You are trying to read from the 64 bit view of the registry but you have a 32 bit process and the redirector means you see the 32 bit view. Pass the KEY_WOW64_64KEY
flag to RegOpenKeyEx
to read from the 64 bit view.
Do beware that strings returned from registry API functions may not be null-terminated. Use the value returned in value_length
to explicitly add a null-terminator.
When you get the code that reads the key sorted you want to delete it. Because it is under HKLM
your process will have to run with admin rights. You will have to use an access flag with sufficient rights to delete, that is more powerful that KEY_READ
in other words.
As an aside, since you chose to use the ANSI API always, the use of the TEXT
macro is misleading. Personally, I'd opt for the Unicode API.