windows核心编程之API拦截

这个是替换自己进程的API

static void WINAPI MySleep(int i)
{
	//((MyTest)g_sleep)(i);

	MessageBoxA(NULL, "1","1",MB_OK);
}
void MyHook()
{
	PSTR pszKernel		= "kernel32.dll";
	PSTR pszSleepName	= "Sleep";
	PSTR pszMessageBoxA = "MessageBoxA";
	PSTR pszUser32		= "user32.dll";


	HMODULE hExeMod		= GetModuleHandle(NULL);
	HMODULE hKernelMod	= GetModuleHandleA(pszKernel);
	HMODULE hUser32		= GetModuleHandleA(pszUser32);

	PROC pfnNew = (PROC)MySleep;
	PROC pfnOld = g_sleep = GetProcAddress(hKernelMod, pszSleepName);

	ULONG ulsize;

	PIMAGE_IMPORT_DESCRIPTOR pImportDesc = 
		(PIMAGE_IMPORT_DESCRIPTOR)ImageDirectoryEntryToData(
		hExeMod,TRUE,IMAGE_DIRECTORY_ENTRY_IMPORT,&ulsize);

	while(pImportDesc->Name)
	{
		PSTR pszModName = 
			(PSTR)((PBYTE)hExeMod + pImportDesc->Name);
		if (strlen(pszModName) != 0)
		{
			PIMAGE_THUNK_DATA pThunk = 
				(PIMAGE_THUNK_DATA)((PBYTE)hExeMod + pImportDesc->FirstThunk);

			while (pThunk->u1.Function)
			{
				PROC* ppFn =(PROC*)&pThunk->u1.Function;

				if(*ppFn == pfnOld)
				{
					MEMORY_BASIC_INFORMATION mbi;
					VirtualQuery(ppFn,
						&mbi,sizeof(mbi));

					VirtualProtect(
						mbi.BaseAddress,
						mbi.RegionSize,
						PAGE_READWRITE,
						&mbi.Protect);
					*ppFn = pfnNew;
					DWORD dwOldProtect;
					VirtualProtect(
						mbi.BaseAddress,
						mbi.RegionSize,
						mbi.Protect,
						&dwOldProtect);

					break;
				}
				pThunk++;
			}
		}
		pImportDesc++;
	}
}


你可能感兴趣的:(windows,api,核心编程)