Example: How to call ReadProcessMemory

Discussion relating to C Sharp (.NET)
Post Reply
User avatar
timb3r
Site Admin
Posts: 15
Joined: Sat Sep 15, 2018 5:35 am
Contact:

Tue Oct 16, 2018 11:42 am

Here's a quick example how you can call ReadProcessMemory from C#.

Code: Select all

using System;
using System.Diagnostics; // Process class
using System.Runtime.InteropServices; // Need this for DllImport

namespace CS_MemoryScan
{
    public enum ProcessAccessFlags : uint
    {
        All                     = 0x001F0FFF,
        Terminate               = 0x00000001,
        CreateThread            = 0x00000002,
        VirtualMemoryOperation  = 0x00000008,
        VirtualMemoryRead       = 0x00000010,
        VirtualMemoryWrite      = 0x00000020,
        DuplicateHandle         = 0x00000040,
        CreateProcess           = 0x000000080,
        SetQuota                = 0x00000100,
        SetInformation          = 0x00000200,
        QueryInformation        = 0x00000400,
        QueryLimitedInformation = 0x00001000,
        Synchronize             = 0x00100000
    }

    class Program
    {
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern IntPtr OpenProcess(ProcessAccessFlags processAccess, bool bInheritHandle, int processId);
        [DllImport("kernel32.dll", SetLastError = true)]
        static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead);
        [DllImport("kernel32.dll", SetLastError = true)]
        public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesWritten);

        public static IntPtr OpenProcess(Process proc, ProcessAccessFlags flags)
        {
            return OpenProcess(flags, false, proc.Id);
        }

        static void Main(string[] args)
        {
            // Retrieve every process called notepad
            Process[] p = Process.GetProcessesByName("notepad");
            if(p.Length > 0) {
                Process notepad = (Process)p.GetValue(0); // We want the first notepad
                Console.WriteLine("pid {0} - {1} was started at {2}", notepad.Id, notepad.ProcessName, notepad.StartTime); // Print the name and start time

                IntPtr hProc = OpenProcess(notepad, ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VirtualMemoryRead);
                if(hProc != null) {
                    IntPtr lpOut;
                    IntPtr Addr = (IntPtr)0x00007FF705020000;
                    byte[] lpBuffer = new byte[128];

                    ReadProcessMemory(hProc, Addr, lpBuffer, 128, out lpOut);

                    foreach(byte b in lpBuffer)
                    {
                        Console.Write("{0:x} ", b);
                    }
                }
            }
            // Wait for input to close
            Console.ReadKey();
        }
    }
}
Post Reply