// InjectDll.h
#pragma once
#include <windows.h>
using namespace System;
namespace InjectDll {
public ref class InjectDllManager
{
public:
// szLibPath - 要加载的Dll,hProcess - 被加载的远程进程,iLibPathSize-要加载的Dll的名称的长度
void InjectLib2Process(char szLibPath[],HANDLE hProcess,int iLibPathSize)
{
HANDLE hThread;
void* pLibRemote;
DWORD hLibModule;//已加载的DLL的基地址(HMODULE);
HMODULE hKernel32 = GetModuleHandle(L"Kernel32");
//初始化 szLibPath
//...
// 1. 在远程进程中为szLibPath 分配内存
// 2. 写szLibPath到分配的内存
pLibRemote = VirtualAllocEx( hProcess, NULL, iLibPathSize,
MEM_COMMIT, PAGE_READWRITE );
WriteProcessMemory( hProcess, pLibRemote, (void*)szLibPath,
sizeof(szLibPath), NULL );
// 加载 "szLibPath.dll" 到远程进程
// (通过 CreateRemoteThread & LoadLibrary)
hThread = CreateRemoteThread( hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) GetProcAddress( hKernel32,
"LoadLibraryA" ),pLibRemote, 0, NULL );
WaitForSingleObject( hThread, INFINITE );
//取得DLL的基地址
GetExitCodeThread( hThread, &hLibModule );
//扫尾工作
CloseHandle( hThread );
VirtualFreeEx( hProcess, pLibRemote, iLibPathSize, MEM_RELEASE );
// 从目标进程卸载LibSpu.dll
// (通过 CreateRemoteThread & FreeLibrary)
hThread = CreateRemoteThread( hProcess, NULL, 0,
(LPTHREAD_START_ROUTINE) GetProcAddress( hKernel32,"FreeLibrary" ),(void*)hLibModule, 0, NULL );
WaitForSingleObject( hThread, INFINITE );
// 扫尾工作
CloseHandle( hThread );
}
};
}