尝试这样的事情:
#include
#include
std::map<:wstring hinstance> libs;
template
bool dynamyc_function(LPCWSTR libname, LPCSTR funcname, T *func)
{
HINSTANCE hlib = libs[libname];
if (!hlib)
{
hlib = LoadLibraryW(libname);
if (!hlib)
{
wprintf(L"could not load the dynamic library %s! %d", libname, GetLastError());
return false;
}
libs[libname] = hlib;
}
*func = (T) GetProcAddress(hlib, funcname);
if (!*func)
{
printf("could not locate the function %s! %d", name, GetLastError());
return false;
}
return true;
}
int main(int argc, char *argv[])
{
typedef HHOOK(__stdcall *f_funci)(int, HOOKPROC, HINSTANCE, DWORD);
// resolve function address here
f_funci SetWindowsHookEx2;
if (!dynamyc_function(L"User32.dll", "SetWindowsHookExW", &SetWindowsHookEx2))
return EXIT_FAILURE;
HHOOK hMouseHook = SetWindowsHookEx2(WH_MOUSE_LL, my_function, hInstance, NULL);
if (!hMouseHook)
{
printf("could not set hook! %d", GetLastError());
return EXIT_FAILURE;
}
...
UnhookWindowsHookEx(hMouseHook);
return 0;
}
或者,如果您只对特定功能感兴趣,可以尝试这样的事情:
typedef HHOOK(__stdcall *f_funci)(int, HOOKPROC, HINSTANCE, DWORD);
HHOOK __stdcall Impl_SetWindowsHookExW(int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD dwThreadId);
HHOOK __stdcall Stub_SetWindowsHookExW(int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD dwThreadId);
f_funci lpSetWindowsHookExW = &Stub_SetWindowsHookExW;
HHOOK __stdcall Impl_SetWindowsHookExW(int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD
{
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return NULL;
}
HINSTANCE hUser32 = NULL;
HHOOK __stdcall Stub_SetWindowsHookExW(int idHook, HOOKPROC lpfn, HINSTANCE hMod, DWORD dwThreadId)
{
if (!hUser32)
{
hUser32 = LoadLibraryW("User32.dll");
if (!hUser32)
{
DWORD err = GetLastError();
printf("could not load the dynamic library! %d", err);
SetLastError(err);
return NULL;
}
}
f_funci func = (f_funci) GetProcAddress(hUser32, "SetWindowsHookExW");
if (!func)
{
DWORD err = GetLastError();
printf("could not locate the function! %d", err);
SetLastError(err);
func = &Impl_SetWindowsHookExW;
}
lpSetWindowsHookExW = func;
return func(idHook, lpfn, hMod, dwThreadId);
}
int main(int argc, char *argv[])
{
HHOOK hMouseHook = lpSetWindowsHookExW(WH_MOUSE_LL, my_function, hInstance, NULL);
if (!hMouseHook)
{
printf("could not set hook! %d", GetLastError());
return EXIT_FAILURE;
}
...
UnhookWindowsHookEx(hMouseHook);
return 0;
}