Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.ComponentModel;
- using System.Diagnostics;
- using System.Runtime.InteropServices;
- using System.Text;
- namespace Rbot
- {
- public class MemoryReader
- {
- const int PROCESS_WM_READ = 0x0010;
- [DllImport("kernel32.dll")]
- public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
- [DllImport("kernel32.dll", SetLastError = true)]
- public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, uint dwSize, out int lpNumberOfBytesRead);
- private IntPtr processHandle;
- public MemoryReader(string gameName)
- {
- Process process = Process.GetProcesses()
- .FirstOrDefault(p => p.ProcessName.IndexOf(gameName, StringComparison.OrdinalIgnoreCase) >= 0);
- if (process != null)
- {
- IntPtr processHandle = OpenProcess(PROCESS_WM_READ, false, process.Id);
- }
- }
- [DllImport("psapi.dll", SetLastError = true)]
- public static extern bool EnumProcessModules(IntPtr hProcess, [Out] IntPtr lphModule, uint cb, out uint lpcbNeeded);
- [DllImport("psapi.dll")]
- public static extern uint GetModuleBaseName(IntPtr hProcess, IntPtr hModule, [Out] char[] lpBaseName, uint nSize);
- public IntPtr GetModuleBaseAddress(string modName)
- {
- IntPtr[] modulePointers = new IntPtr[1024];
- GCHandle gch = GCHandle.Alloc(modulePointers, GCHandleType.Pinned);
- IntPtr pModules = gch.AddrOfPinnedObject();
- if (EnumProcessModules(processHandle, pModules, (uint)(modulePointers.Length * IntPtr.Size), out uint _))
- {
- char[] moduleName = new char[1024];
- for (int i = 0; i < modulePointers.Length; i++)
- {
- if (modulePointers[i] == IntPtr.Zero)
- {
- continue;
- }
- GetModuleBaseName(processHandle, modulePointers[i], moduleName, (uint)moduleName.Length);
- if (modName.Equals(new string(moduleName).TrimEnd('\0')))
- {
- gch.Free();
- return modulePointers[i];
- }
- }
- }
- gch.Free();
- return IntPtr.Zero;
- }
- public IntPtr GetAbsoluteAddress(IntPtr moduleBaseAddress, int offset)
- {
- return new IntPtr(moduleBaseAddress.ToInt32() + offset);
- }
- public long GetFinalAddress(IntPtr baseAddress, int[] offsets)
- {
- byte[] buffer = new byte[IntPtr.Size];
- foreach (int offset in offsets)
- {
- IntPtr tempAddress = IntPtr.Add(baseAddress, offset);
- buffer = ReadMemory(tempAddress.ToInt64(), 4);
- if (buffer.Length >= IntPtr.Size)
- {
- baseAddress = (IntPtr.Size == 4) ? new IntPtr(BitConverter.ToInt32(buffer, 0)) : new IntPtr(BitConverter.ToInt64(buffer, 0));
- }
- }
- return baseAddress.ToInt64();
- }
- public byte[] ReadMemory(long address, int size)
- {
- byte[] buffer = new byte[size];
- IntPtr ptr = new IntPtr(address);
- ReadProcessMemory(processHandle, ptr, buffer, (uint)buffer.Length, out int bytesRead);
- return buffer;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement