0

I am trying to set a global GetMessage hook on all threads. This is my DLL:

#include <windows.h>

__declspec(dllexport) LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
  MessageBeep(0);

  return CallNextHookEx(NULL, nCode, wParam, lParam);
}

As you can see, it's not much. I just want it to call MessageBeep whenever it's called.

#include <windows.h>

typedef LRESULT (CALLBACK *LPGetMsgProc)(int nCode, WPARAM wParam, LPARAM lParam);

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR pCmdLine, int nCmdShow)
{
  if(!(HMODULE hDll = LoadLibrary("library.dll")))
    return 1;
  if(!(LPGetMsgProc pfnProc = (LPGetMsgProc)GetProcAddress(hDll, "GetMsgProc@12")))
    return 2;

  HHOOK hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, pfnProc, hInstance, 0);

  MSG msg;
  while(GetMessage(&msg, NULL, 0, 0) > 0) {}

  UnhookWindowsHookEx(hMsgHook);

  return 0;
}

My WinMain loads the library, gets the procedure and sets the hook. However, MessageBeep is never being called. Is there something I'm doing wrong here?

Also, one other thing has been bothering me. In this call:

if(!(LPGetMsgProc pfnProc = (LPGetMsgProc)GetProcAddress(hDll, "GetMsgProc@12")))

I was forced to use "GetMsgProc@12" because I couldn't get it right any other way. Can somebody please tell me how I'm supposed to use a .def file or something else so I can just have it as "GetMsgProc"? Though MSDN stated that since I have __declspec(dllexport) in my declaration I wouldn't need it...

My IDE is Code::Blocks with MinGW. Thanks in advance.

kaykun
  • 2,247
  • 2
  • 24
  • 37
  • To answer your last question, you want to use `extern "C"` to prevent the name-mangling. Not sure about the first one yet though; have you verified that you're actually being sent any messages? – Shog9 Jul 09 '10 at 03:05
  • Both the DLL and EXE are coded and compiled in C, so I can't use extern "C". I would think that I'd be able to switch to any program, click anywhere to send a message and it would call my GetMsgProc. However, as MessageBeep isn't being called, this isn't the case. – kaykun Jul 09 '10 at 03:10
  • Eh, I'm wrong anyway. See: http://stackoverflow.com/questions/366228/def-files-c-c-dlls – Shog9 Jul 09 '10 at 03:20
  • I'm not seeing anything in there that solves the problem. I can't use extern "C", and I've already declared __declspec(dllexport). – kaykun Jul 09 '10 at 03:45
  • Read the last answer - apparently, some calling conventions will still mangle names if you don't list them in a def file. – Shog9 Jul 09 '10 at 07:49

1 Answers1

3

The third parameter...

HHOOK hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, pfnProc, hInstance, 0);

...is the handle passed into your WinMain function. But it needs to refer to the DLL where the callback function resides - in your case, that'd be hDLL.

Shog9
  • 156,901
  • 35
  • 231
  • 235