我正在为WH_GETMESSAGE编写一个全局钩子。但是当从dll调用GetProcAddress函数时,我得到错误代码127,即ERROR_PROC_NOT_FOUND。它无法找到GetMsgProc。知道为什么吗?
此外,我是这种编程的新手,所以对任何不期望的错误道歉。
DLL文件:
#include "windows.h"
#include <stdio.h>
BOOL APIENTRY DllMain(HANDLE hModule, DWORD ul_reason_for_call, LPVOID lpReserved)
{
return TRUE;
}
__declspec(dllexport) LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MessageBox(NULL, TEXT("I am in"),TEXT("In a DLL"), MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
程序加载DLL文件:
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
typedef LRESULT(CALLBACK *LPGetMsgProc)(int nCode, WPARAM wParam, LPARAM lParam);
int main()
{
HMODULE hDll = LoadLibrary(_T("../../dllTouchInputHook/x64/Debug/dllTouchInputHook.dll"));
LPGetMsgProc proc = (LPGetMsgProc)GetProcAddress(hDll, "GetMsgProc");
if (proc == NULL) {
printf("The error code is %d", GetLastError());
}
HHOOK hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, proc, hDll, 0);
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
UnhookWindowsHookEx(hMsgHook);
return 0;
}
答案 0 :(得分:4)
找不到该功能,因为它没有像您期望的那样导出为"GetMsgProc"
。它的实际输出更像是"_GetMsgProc@12"
(32位)或"_GetMsgProc@20"
(64位)。如果您希望将其导出为"GetMsgProc"
,那么在编译DLL时需要使用.DEF
文件。
你不应该以这种方式实现钩子。您应该将调用移动到DLL本身内的SetWindowsHookEx()
,然后导出一个函数来调用它,例如:
#include "windows.h"
#include <stdio.h>
HINSTANCE hThisDLL;
HHOOK hMsgHook;
BOOL APIENTRY DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved)
{
hThisDLL = hinstDLL;
return TRUE;
}
LRESULT CALLBACK GetMsgProc(int nCode, WPARAM wParam, LPARAM lParam)
{
MessageBox(NULL, TEXT("I am in"), TEXT("In a DLL"), MB_OK);
return CallNextHookEx(NULL, nCode, wParam, lParam);
}
__declspec(dllexport) BOOL WINAPI InstallHook()
{
if (!hMsgHook)
hMsgHook = SetWindowsHookEx(WH_GETMESSAGE, &GetMsgProc, hThisDll, 0);
return (hMsgHook != NULL);
}
__declspec(dllexport) VOID WINAPI UninstallHook()
{
if (hMsgHook)
{
UnhookWindowsHookEx(hMsgHook);
hMsgHook = NULL;
}
}
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
typedef BOOL (WINAPI *LPInstallHook)();
typedef VOID (WINAPI *LPUninstallHook)();
int main()
{
HMODULE hDll = LoadLibrary(_T("../../dllTouchInputHook/x64/Debug/dllTouchInputHook.dll"));
if (!hDll)
{
printf("The error code is %d", GetLastError());
return -1;
}
LPInstallHook installProc = (LPInstallHook) GetProcAddress(hDll, "InstallHook"); // or "_InstallHook"
LPUninstallHook uninstallProc = (installProc) ? (LPUninstallHook) GetProcAddress(hDll, "UninstallHook") : NULL; // or "_UninstallHook"
if (!(installProc && uninstallProc))
{
printf("The error code is %d", GetLastError());
FreeLibrary(hDll);
return -1;
}
if (!installProc())
{
printf("The error code is %d", GetLastError());
FreeLibrary(hDll);
return -1;
}
MSG msg;
while (GetMessage(&msg, NULL, 0, 0) > 0) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
uninstallProc();
FreeLibrary(hDll);
return 0;
}