willygstyle 5 Junior Poster in Training

Ok so I have my .dll working correctly however I can't get my hook to load properly. When I use GetLastError() to figure out what went wrong I get error code 1428.

ERROR_HOOK_NEEDS_HMOD 1428 (0x594)
Cannot set nonlocal hook without a module handle.

I've seen a ton of examples that seem to use GetModuleHandle(NULL) which is what I'm using and it seems to match the address in main and in the .dll so not sure what's going wrong here??? Here is my current code.

.DEF

LIBRARY KBHOOK.dll
EXPORTS
    foo @1
    InstallHook @2
    RemoveHook @3

SECTIONS
SharedBlock READ WRITE SHARED

.h

#ifndef _RESOURCE_H
#define _RESOURCE_H
#include <iostream>
#include <string>
#include <stdio.h>
#include <windows.h>
#pragma once

extern "C" void foo();
extern "C" void InstallHook();
extern "C" void RemoveHook();
LRESULT CALLBACK Keyboard_Proc(int code, WPARAM wParam, LPARAM lParam);


#endif

.cpp

#include "resource.h"

#pragma data_seg("SharedBlock")
HHOOK Keyboard_Hook = NULL;
HMODULE ThisModule = NULL;
#pragma data_seg()

#define HK_IS_PRESSED ((DWORD)lParam & 0x40000000)
#define HK_IS_HELD ((DWORD)lParam & 0x40000000)
#define HK_IS_RELEASED (!((DWORD)lParam & 0x40000000))


LRESULT CALLBACK Keyboard_Proc(int code, WPARAM wParam, LPARAM lParam)
{
    std::cout << "IN CALLBACK\n";
    if(code > 0) return CallNextHookEx(Keyboard_Hook, code, wParam, lParam);
    else if (code == HC_ACTION)
    {
        std::cout << "HC ACTION PASSED\n";
        if (HK_IS_PRESSED)
        {
            std::cout << "YOU PRESSED A KEY\n";
            // Key was pressed, VK_KEY code is in wParam.
        }
        else if (HK_IS_HELD)
        {

        }
        else if (HK_IS_RELEASED)
        {

        }
    }

    return CallNextHookEx(Keyboard_Hook, code, wParam, lParam);
}

extern "C" void foo()
{
    std::cout << "HELLO\n";
}


extern "C"  void InstallHook()
{
    ThisModule = GetModuleHandle(NULL);
    std::cout << ThisModule << " in install\n";
    //GetCurrentThreadId() can be set to 0 for system wide hook
    Keyboard_Hook = SetWindowsHookEx(WH_KEYBOARD, Keyboard_Proc, ThisModule,0);
    if(Keyboard_Hook == NULL)
    {
        std::cout << "HOOK NOT SET\n";
        std::cout << GetLastError();
    }
    else
    {
        std::cout << "HOOK SET\n";
    }
}

extern "C" void RemoveHook()
{
    UnhookWindowsHookEx(Keyboard_Hook);
}

Any help appreciated.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.