Thread: How to keep static data in a keyboard hook?

  1. #1
    Registered User
    Join Date
    Jul 2002

    Question How to keep static data in a keyboard hook?

    I created a simple DLL to do a global keyboard hook, but I was unable to communicate data between the procedure which set up the hook and the hook itself:

    HHOOK hKeyboardHook = NULL;
    int i = 0;

    LRESULT CALLBACK KeyboardHookProc(int code, WPARAM wParam, LPARAM lParam) {
    if (code < 0)
    return CallNextHookEx(hKeyboardHook, code, wParam, lParam);

    if (i = 0) {

    return 0;

    extern "C" HHOOK CFHookKeyboard(void) {
    if (!hKeyboardHook)
    hKeyboardHook = SetWindowsHookEx(WH_KEYBOARD, KeyboardHookProc, (HINSTANCE)hMod, 0);

    i = 1;

    return hKeyboardHook;

    Anyone knows of any fix?

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    The problem you have is that each dll will have a seperate copy of the process of the app that creates the hook, it will be valid, but in all other instances if will be void........

    Many compilers offer a global memory option for dlls - kind of like a static variable in a c++ class - you can have as many dlls running in the system as you need, but they all refer to one area of system that shared area, you place the HHOOK

    For VC++ you use;

    #pragma data_seg(".syshook") //Set shareable segment
    HHOOK hKeyboardHook = NULL; //Handle to my hook
    #pragma data_seg()
    #pragma comment(linker, "/section:.syshook,rws")
    Now every dll uses the same HHOOK......

    Also add to this that the hook procedure (when called) exists in another process.........that means all shared handles (file...etc) are unusable (and you cant share them accross process boundries as you dont have a list of the processes that need them)...they way I get around this is for the launching app to open a MailSlot (CreateMailSlot()) and then create a thread to recieve messages......then I use CreateFile() in the hook dll to get a handle to the Mailslot (which is usable in my process) and write output to it.......

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Simulate Keys with a Keyboard Hook
    By guitarist809 in forum Windows Programming
    Replies: 3
    Last Post: 11-14-2008, 08:14 PM
  2. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  3. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  4. Linking errors with static var
    By Elysia in forum C++ Programming
    Replies: 8
    Last Post: 10-27-2007, 05:24 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM