http://www.jarloo.com/reading-and-writing-to-memory/
Declarations
[Flags] public enum ProcessAccessFlags : uint { All = 0x001F0FFF, Terminate = 0x00000001, CreateThread = 0x00000002, VMOperation = 0x00000008, VMRead = 0x00000010, VMWrite = 0x00000020, DupHandle = 0x00000040, SetInformation = 0x00000200, QueryInformation = 0x00000400, Synchronize = 0x00100000 } [DllImport("kernel32.dll")] private static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten); [DllImport("kernel32.dll", SetLastError = true)] static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out int lpNumberOfBytesRead); [DllImport("kernel32.dll")] public static extern Int32 CloseHandle(IntPtr hProcess);
Reading from another processes Memory
public static byte[] ReadMemory(Process process, int address, int numOfBytes, out int bytesRead) { IntPtr hProc = OpenProcess(ProcessAccessFlags.All, false, process.Id); byte[] buffer = new byte[numOfBytes]; ReadProcessMemory(hProc, new IntPtr(address), buffer, numOfBytes, out bytesRead); return buffer; }
Here is an example of a call to this function:
Process process = Process.GetProcessesByName("My Apps Name").FirstOrDefault(); int address = 0x02ED2910; int bytesRead; byte[] value = ReadMemory(process, address, 4, out bytesRead);
Writing to another processes memory
public static bool WriteMemory(Process process, int address, long value, out int bytesWritten) { IntPtr hProc = OpenProcess(ProcessAccessFlags.All, false, process.Id); byte[] val = BitConverter.GetBytes(value); bool worked = WriteProcessMemory(hProc, new IntPtr(address), val, (UInt32) val.LongLength, out bytesWritten); CloseHandle(hProc); return worked; }
Here is an example of a call to this function:
Process process = Process.GetProcessesByName(
"My Apps Name"
).FirstOrDefault();
int
address = 0x02ED2910;
int
bytesWritten;
bool
worked = WriteMemory(process, address, value,
out
bytesWritten);
函数功能:该函数从指定的进程中读入内存信息,被读取的区域必须具有访问权限。
函数原型:BOOL ReadProcessMemory(HANDLE hProcess,LPCVOID lpBaseAddress,LPVOID lpBuffer,DWORD nSize,LPDWORD lpNumberOfBytesRead);
参数:
hProcess:进程句柄
lpBaseAddress:读出数据的地址
lpBuffer:存放读取数据的地址
nSize:读出的数据大小
lpNumberOfBytesRead:数据的实际大小
C#中使用该函数首先导入命名空间:
然后写API引用部分的代码,放入 class 内部
这个函数有五个参数,第一个参数是 进程句柄,由OpenProcess函数获取;第二个参数是要读出数据的地址,使用CE等辅助工具可取得;第三个参数是用于存放读取数据的地址;第四个参数是 要读出的数据大小;第五个参数是读出数据的实际大小。例如:
如果我们读取的一段内存中的数据,我们引入部分可修改成如下:
由于数组是引用传递,我们不需要写out关键字。