我正在探索写入/读取进程内存,并编写了一个模拟健康的简单程序,就好像它是一个游戏。我想通过内存写入将 health int 重写为不同的东西,但我无法显示进程快照,这也可能导致附加到进程的问题。带有简单“游戏”的代码,它被编译为 Target.exe:
#include<iostream>
#include<windows.h>
int main() {
int hp = 100;
while (true) {
hp -= 1;
std::cout << hp << "\n";
Sleep(3000);
}
return 0;
}
进程附加和内存编辑代码:
#include <iostream>
#include <windows.h>
#include <tlhelp32.h>
HANDLE hProc; // handle to the process
DWORD pID; // process id
bool attachProc(char* procName) { // create a boolean function that attaches to a process with procname
PROCESSENTRY32 procEntry32;
// defining the size so we can populate it
procEntry32.dwSize = sizeof(PROCESSENTRY32);
// taking a snapshot of all processes running
auto hProcSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (hProcSnap == INVALID_HANDLE_VALUE)
{
// if snapshot failed and got an invalid handle value
std::cout << "Failed to take snapeshot" << std::endl;
return false;
}
while (Process32Next(hProcSnap, &procEntry32))
{ // create a while loop to loop through the list of proceses
// while there is a next process, we will keep looping
std::cout << (char*)procEntry32.szExeFile << std::endl; //output the name of the file it is currently at
if (!strcmp(procName, procEntry32.szExeFile))
{
std::cout << "Found process" << procEntry32.szExeFile << " wtih process Id " << procEntry32.th32ProcessID;
hProc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, procEntry32.th32ProcessID);
pID = procEntry32.th32ProcessID;
if (hProc == NULL)
{
std::cout << "Failed getting handle to process";
}
// if procEntry32 is an error change project settings to use a multi-byte chatacter set
// visual studio go to project > project name properties > config properties > advanced > change char set to multi-byte
CloseHandle(hProcSnap);
return true;
}
std::cout << "Could find " << procName << " in the process snapshot" << std::endl;
CloseHandle(hProcSnap);
return false;
}
}
// write wrappers for writing and reading process memory
template <class dataType>
void wpm(dataType valToWrite, DWORD adressToWrite) {
WriteProcessMemory(hProc, (PVOID)adressToWrite, &valToWrite, sizeof(dataType), 0);
}
template <class dataType>
dataType rpm(DWORD adressToRead) {
dataType rpmBuffer;
ReadProcessMemory(hProc, (PVOID)adressToRead, &rpmBuffer, sizeof(dataType), 0);
return rpmBuffer;
}
int main() {
DWORD memoryAdress = 0x50947BFD14;
attachProc((char*)"Target.exe");
while (true)
{
wpm<int>(100, memoryAdress);
}
}