global mouse hook causes application crash (c++ / windows7)

753 views Asked by At

I'm trying to write a dll to inject a global mouse hook in Windows 7. It basically works, but after some seconds (maybe 10 - 15) the whole application just freezes up and the mouse wont work outside Visual Studio (I can still stop the app via vs but nothing else (like using the task manager to do it)).

I've been searching for some time now but I can't really find an answer to my problem. I've reduced my dll to the bare minimum (install the mouse hook without doing anything with it) but it still happens.

header

#ifndef MOUSE_HOOK_WINDOWS_H
#define MOUSE_HOOK_WINDOWS_H

#if defined DLL_EXPORT
    #define DECLDIR __declspec(dllexport)
#else
    #define DECLDIR __declspec(dllimport)
#endif

#pragma data_seg(".mouseHookSharedMemory")
    HHOOK g_hMouseHook = NULL;
    HINSTANCE g_hInst = NULL;
#pragma data_seg()
#pragma comment(linker, "/section:.mouseHookSharedMemory,RWS")

extern "C"
{
    DECLDIR BOOL InstallHook();
    DECLDIR BOOL UninstallHook();

    LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam);
}

#endif

cpp

#include <Windows.h>
#include "MouseHookWindows.h"

#include <sstream>

extern "C"
{
    DECLDIR BOOL InstallHook()
    {
        if(g_hMouseHook != NULL)
        {
            return true;
        }

        g_hMouseHook = SetWindowsHookEx(WH_MOUSE, MouseProc, g_hInst, 0);
        if(g_hMouseHook == NULL)
        {
            return false;
        }

        return true;
    }

    DECLDIR BOOL UninstallHook()
    {
        if(g_hMouseHook != NULL)
        {
            UnhookWindowsHookEx(g_hMouseHook);
            g_hMouseHook = NULL;
        }  

        return true;
    }

    LRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
    {
        return CallNextHookEx(g_hMouseHook, nCode, wParam, lParam);
    }
}

BOOL APIENTRY DllMain(HINSTANCE hInstance, DWORD reason, LPVOID reserved)
{
    g_hInst = hInstance;

    return true;
}

There's no exception or anything. The application freezes and everything but visual studio wont react to the mouse anymore (as said before, not even the task manager)

I don't know whether it's important but I use the dll in a c++ console application.

Thanks in advance Manuel

1

There are 1 answers

0
wrongway On BEST ANSWER

user2802841 was right, the problem was the missing message loop. When using a mouse hook (WH_MOUSE or WH_MOUSE_LL) in a console application getMessage or peekMessage have to be called somewhere in the application.