Reading or Writing to Another Processes Memory in C# 转载

https://www.cnblogs.com/zeroone/p/3766247.html

[Flags]
public enum ProcessAccessFlags : uint
{
    All = 0x001F0FFF,
    Terminate = 0x00000001,
    CreateThread = 0x00000002,
    VMOperation = 0x00000008,
    VMRead = 0x00000010,
    VMWrite = 0x00000020,
    DupHandle = 0x00000040,
    SetInformation = 0x00000200,
    QueryInformation = 0x00000400,
    Synchronize = 0x00100000
}
 
[DllImport("kernel32.dll")]
private static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
 
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out int lpNumberOfBytesWritten);
 
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out int lpNumberOfBytesRead);
 
[DllImport("kernel32.dll")]
public static extern Int32 CloseHandle(IntPtr hProcess);

复制代码
Reading from another processes Memory

复制代码
public static byte[] ReadMemory(Process process, int address, int numOfBytes, out int bytesRead)
{
    IntPtr hProc = OpenProcess(ProcessAccessFlags.All, false, process.Id);
 
    byte[] buffer = new byte[numOfBytes];
 
    ReadProcessMemory(hProc, new IntPtr(address), buffer, numOfBytes, out bytesRead);
    return buffer;
}

复制代码
Here is an example of a call to this function:

Process process = Process.GetProcessesByName("My Apps Name").FirstOrDefault();
int address = 0x02ED2910;

int bytesRead;
byte[] value = ReadMemory(process, address, 4, out bytesRead);
Writing to another processes memory

复制代码
public static bool WriteMemory(Process process, int address, long value, out int bytesWritten)
{
    IntPtr hProc = OpenProcess(ProcessAccessFlags.All, false, process.Id);
             
    byte[] val = BitConverter.GetBytes(value);
             
    bool worked = WriteProcessMemory(hProc, new IntPtr(address), val, (UInt32) val.LongLength, out bytesWritten);
 
    CloseHandle(hProc);
 
    return worked;
}
复制代码

Here is an example of a call to this function:

Process process = Process.GetProcessesByName("My Apps Name").FirstOrDefault();
int address = 0x02ED2910;

int bytesWritten;
bool worked = WriteMemory(process, address, value, out bytesWritten);

posted @ 2023-02-10 05:32  dewxin  阅读(21)  评论(0编辑  收藏  举报