user2020040
user2020040

Reputation:

Why won't my registry read work vc++?

I am using the following code:

bool DllGuard()
{
    HKEY keyHandle;
    bool rgValue = bool();
    DWORD Size;
    DWORD Type;

    try
    {
        if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\MSB", 0, KEY_QUERY_VALUE, &keyHandle) == ERROR_SUCCESS)
        {
            Type = REG_DWORD;

            Size = sizeof(DWORD);

            RegQueryValueEx(keyHandle, "DllGuard", NULL, &Type, (LPBYTE)rgValue,&Size);
        }     

        RegCloseKey(keyHandle);

        if (rgValue == false)
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    catch (...)
    {
        return false;
    }
}

BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD fdwReason, LPVOID lpReserved)
{
    if(fdwReason == DLL_PROCESS_ATTACH)
    {
        if (DllGuard())
        {
            DisableThreadLibraryCalls(hInstance);
            CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&Main, NULL, 0, NULL);
        }
        else
        {
            exit(0);
        }
    }
    return TRUE;
}

First time around it works fine, thus creating the thread in DllMain.

The second time around, it does not work as it still creates the thread in DllMain even if the registry key is set to true.

Help!

Thanks!

Upvotes: 0

Views: 179

Answers (2)

lmiguelmh
lmiguelmh

Reputation: 3202

I can't comment but I think is important to know that you should consider not using DLLMain at all unless you know what you are doing... Give a look at the MSDN pages for DllMain entry point:

Warning There are serious limits on what you can do in a DLL entry point. To provide more complex initialization, create an initialization routine for the DLL. You can require applications to call the initialization routine before calling any other routines in the DLL.

Or you can Be afraid. Be very afraid

Upvotes: 0

Anton Kovalenko
Anton Kovalenko

Reputation: 21507

(LPBYTE)rgValue shoud be (LPBYTE)&rgValue, as you want to pass a pointer (so rgValue is modified by RegQueryValueEx. And it should be DWORD rgValue instead of bool (maybe you know that they happen to be of the same size, but it's harder to read).

Also it would be great to check the return value of RegQueryValueEx, so we have a chance to know what's wrong next time when it fails. (If you have no idea how to handle a failure, maybe write something with OutputDebugString, to be seen in sysinternals' dbgview.exe).

Upvotes: 1

Related Questions