核心编程上一个关于API拦截的例子,出了点问题,求解
首先上代码
- C/C++ code
#include "stdafx.h"#include <Windows.h>#include <iostream>#include <cstdlib>#include <Dbghelp.h>#pragma comment(lib,"Dbghelp.lib")using namespace std;VOID ReplaceATEntryInOneMod(LPSTR pszCalleeModName,PROC pfnCurrent,PROC pfnNew,HMODULE hModCaller){ ULONG ulSize; PIMAGE_IMPORT_DESCRIPTOR pImportDesc = NULL; __try { pImportDesc = (PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToDataEx(hModCaller,TRUE,IMAGE_DIRECTORY_ENTRY_IMPORT,&ulSize); } __finally { } if(pImportDesc == NULL) { return ; } for(; pImportDesc->Name ; pImportDesc++ ) { PSTR pszModName = (PSTR)((PBYTE)hModCaller + pImportDesc->Name); if(lstrcmpiA(pszModName,pszCalleeModName) == 0) { PIMAGE_THUNK_DATA pThunk = (PIMAGE_THUNK_DATA)((PBYTE)hModCaller + pImportDesc->FirstThunk); for(; pThunk->u1.Function ; pThunk ++ ) { PROC* ppfn = (PROC*)&pThunk->u1.Function; BOOL bFound = (*ppfn == pfnCurrent); if(bFound) { if(!WriteProcessMemory(GetCurrentProcess(),ppfn,&pfnNew,sizeof(pfnNew),NULL) && (ERROR_NOACCESS == GetLastError())) { DWORD dwOldProter; if(!VirtualProtect(ppfn,sizeof(pfnNew),PAGE_WRITECOPY,&dwOldProter)) { WriteProcessMemory(GetCurrentProcess(),ppfn,&pfnNew,sizeof(pfnNew),NULL); VirtualProtect(ppfn,sizeof(pfnNew),dwOldProter,&dwOldProter); } } return ; } } } }}int MyMessageBox(HWND hWnd,LPCSTR lpText,LPCSTR lpCaption,UINT uType){ MessageBeep(0); return 0;}int _tmain(int argc, _TCHAR* argv[]){ PROC pfnOrig = GetProcAddress(GetModuleHandle(_T("User32")),"MessageBoxA"); cout << GetLastError() << endl; HMODULE hModCaller = GetModuleHandle(_T("Test.exe")); ReplaceATEntryInOneMod("user32.dll",pfnOrig,(PROC)MyMessageBox,hModCaller); system("pause"); return 0;}代码问题出现在了GetModuleHandle(_T("Test.exe"));上,GetLastError一直返回的是找不到指定的模块,我以前也没有在里面用过exe的,Test.exe也是放在当前目录下的,求指点这个问题怎么解决,感激不尽。
[解决办法]
调试模式下的工作目录不是exe所在目录,而是工程目录,你在工程选项里调一下,调试这一栏,把工作目录改成test.exe的目录就行了
[解决办法]
会不会是这个问题?
前提是:只有欲获取的模块已映射到调用该函数的进程内,才会正确得到模块句柄。常用模块映射函数:LoadLibrary(..)。
参见 百度百科 。http://baike.baidu.com/view/1286954.htm
[解决办法]