Skip to main content
 首页 » 编程设计

c#之使用 C# 读取进程内存

2024年02月23日22kuangbin

我正在编写一个程序来创建一个进程,然后读取他的一些内存。为了获取地址,我使用了调试器 OllyDbg。

using System; 
using System.Runtime.InteropServices; 
using System.Diagnostics; 
 
namespace winapi 
{ 
    class Program 
    { 
        [DllImport("kernel32.dll", SetLastError = true)] 
        static extern bool ReadProcessMemory( 
          IntPtr hProcess, 
          IntPtr lpBaseAddress, 
          [Out] byte[] lpBuffer, 
          int dwSize, 
          out UInt32 lpNumberOfBytesRead 
         ); 
 
 
        static void Main() 
        { 
            Console.WriteLine("WinAPI test"); 
            Console.WriteLine("---"); 
            Console.WriteLine(); 
 
            var startInfo = new ProcessStartInfo { FileName = "Program.exe" }; 
            Process p = Process.Start(startInfo); 
            var bytes = new byte[4]; 
            uint read = 0; 
            p.WaitForInputIdle(); 
            //   
 
            while (read == 0) 
            { 
                ReadProcessMemory(p.MainWindowHandle, (IntPtr)0x052f820, bytes, bytes.Length, out read);     
                System.Threading.Thread.Sleep(10); 
            } 
 
            Console.WriteLine(read.ToString()); 
            Console.ReadLine(); 
        } 
    } 
} 

进程开始后,我的循环永远不会结束。 来自调试器的数据:

0052F820 | 75 2F 3F 72 61 67 65 5F 69 64 3D 31 33 

我的错误在哪里?

请您参考如下方法:

@zmbq 已经提供了答案。 ReadProcessMemory 的行为不像 Stream,其中每个读取操作都会将总读取计数添加到流位置。

我仍然可以看到代码的另一个问题,您传递的是 Window handle 而不是 process handle。所以即使你得到了结果,它实际上并不是在读取你的目标进程的内存。