using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace TemuKJD.BLL { public class MemoryReader { [DllImport("kernel32.dll")] public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesRead); [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out uint lpNumberOfBytesWritten); [DllImport("kernel32.dll")] public static extern bool CloseHandle(IntPtr hObject); // 声明GetLastError函数 [DllImport("kernel32.dll")] private static extern int GetLastError(); const int PROCESS_WM_READ = 0x0010; const int PROCESS_WM_WRITE = 0x0020; const int PROCESS_WM_ALL = 0x003F; const int PROCESS_ALL_ACCESS = 0x1F0FFF; public static void ReadMemory(int nProcess, int nAddress, int nReadSize) { int processId = nProcess; // 目标进程ID //IntPtr hProcess = OpenProcess(PROCESS_WM_READ | PROCESS_WM_WRITE, false, processId); IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, processId); if (hProcess == IntPtr.Zero) { int errorCode = GetLastError(); //Console.WriteLine("Process access failed."); BaseForms.BaseMsgForm.ShowError("Process access failed."); return; } int endAddress = nAddress + nReadSize; while (nAddress < endAddress) { IntPtr address = new IntPtr(nAddress); // 目标内存地址 byte[] buffer = new byte[1024]; // 读取数据的缓冲区 uint bytesRead; if (ReadProcessMemory(hProcess, address, buffer, (uint)buffer.Length, out bytesRead)) { //Console.WriteLine("Read successful."); string s = System.Text.Encoding.Default.GetString(buffer); if (s.Contains("pddidResult")) { } } else { //Console.WriteLine("Read failed."); // 获取最后一个错误代码 int errorCode = GetLastError(); //Console.WriteLine("Error code: " + errorCode); // 将错误代码转换为异常(可选) Exception ex = Marshal.GetExceptionForHR(errorCode); //BaseForms.BaseMsgForm.ShowError(ex.Message); } nAddress += 1000; } //CloseHandle(hProcess); } } }