# LoadLibrary注入DLL

  • https://www.youtube.com/watch?v=IBwoVUR1gt8
  • https://www.youtube.com/watch?v=PZLhlWUmMs0
#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>

using namespace std;

DWORD GetPID(const wchar_t* name)
{
	DWORD pid = 0;
	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnap != INVALID_HANDLE_VALUE)
	{
		PROCESSENTRY32 pe;
		pe.dwSize = sizeof(pe);
		if (Process32First(hSnap, &pe))
		{
			do
			{
				if (!_wcsicmp(pe.szExeFile, name))
				{
					pid = pe.th32ProcessID;
					break;
				}
			} while (Process32Next(hSnap, &pe));
		}
	}
	CloseHandle(hSnap);
	return pid;
}

int main()
{
	// 1. 获取游戏进程id
	// 2. 获取游戏进程句柄
	// 3. 在游戏进程中申请一块虚拟内存
	// 4. 将dll路径写入申请的内存中
	// 5. 在游戏进程中创建一个线程,调用LoadLibrary函数加载dll
	// 6. 清理资源

	const char* dllpath = "C:\\Users\\ajanuw\\Desktop\\EmptyDll\\Release\\EmptyDll.dll";
	int nSize = strlen(dllpath) + 1;

	const wchar_t* name = L"game2.exe";
	DWORD pid = 0;
	while (pid == 0)
	{
		pid = GetPID(name);
		Sleep(40);
	}
	cout << "pid: " << pid << endl;

	HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, 0, pid);
	if (!hProcess) return 0;


	LPVOID pDLLPathAddr = VirtualAllocEx(hProcess, 0, nSize, 
		MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
	cout << "pDLLPathAddr: " << pDLLPathAddr << endl;

	WriteProcessMemory(hProcess, pDLLPathAddr, dllpath, nSize, 0);

	HANDLE hThread = CreateRemoteThread(hProcess, 0, 0,
		(LPTHREAD_START_ROUTINE)LoadLibraryA, pDLLPathAddr,
		0, 0);

	cout << "hThread: " << hThread << endl;
	WaitForSingleObject(hThread, INFINITE);
	
	VirtualFreeEx(hProcess, pDLLPathAddr, 0, MEM_RELEASE);
	CloseHandle(hThread);
	CloseHandle(hProcess);

	cout << "释放资源完毕" << endl;
	return 0;
}