tags:

views:

36

answers:

1

My program uses SetWindowsHookEx to set a global hook function in my DLL. However I want the DLL to work with a file so I need it a file to be opened once. I can't use DllMain's DLL_PROCESS_ATTACH because it's called multiple times. What is the best solution to my problem?

+1  A: 

Use a static flag to tell whether you've initialized already or not.

void DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) {
    static BOOL initialized = FALSE;

    switch(dwReason) {
        case DLL_PROCESS_ATTACH:
            if(!initialized) {
                // Perform initialization here...ex: open your file.
                initialized = TRUE;
            }
            break;
        case DLL_PROCESS_DETACH:
            if(initialized) {
                // Perform cleanup here...ex: close your file.
                initialized = FALSE;
            }
            break;
    };

}
ntcolonel