I am writing a program that creates a process and then read some bits of his memory. To get the address, I used the debugger 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();
}
}
}
after the process started, my loop never ends.
data from the debugger:
0052F820 | 75 2F 3F 72 61 67 65 5F 69 64 3D 31 33
where is my mistake?
Answer is already provided by @zmbq. ReadProcessMemory does not behave like Stream, where every read operation adds the total read count to the stream position.
I can still see another problem with the code, you are passing Window handle instead of the process handle. So even if you get the result, it is not actually reading memory of your target process.