利用 P/Invoke 呼叫 Kernel32.dll 三大 API,實現跨進程記憶體讀寫。本文說明核心 API 簽名、完整範例與安全/法律風險警示。
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint dwSize, out IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint dwSize, out IntPtr lpNumberOfBytesWritten);
常用存取權旗標:PROCESS_VM_READ (0x0010) | PROCESS_VM_WRITE (0x0020) | PROCESS_VM_OPERATION (0x0008) | PROCESS_QUERY_INFORMATION (0x0400) → 組合常用 0x1F0FFF (全存取)。
class Program
{
static void Main()
{
int targetValue = 999;
IntPtr addr = Marshal.UnsafeAddrOfPinnedArrayElement(new[] { targetValue }, 0); // 取得區域變數位址 (僅示意)
IntPtr hProc = OpenProcess(0x1F0FFF, false, (uint)Process.GetCurrentProcess().Id);
if (hProc == IntPtr.Zero) { Console.WriteLine("OpenProcess 失敗: " + Marshal.GetLastWin32Error()); return; }
byte[] buffer = new byte[4];
IntPtr bytesRead;
if (ReadProcessMemory(hProc, addr, buffer, 4, out bytesRead))
Console.WriteLine($"讀取值: {BitConverter.ToInt32(buffer, 0)}"); // 999
byte[] newVal = BitConverter.GetBytes(100);
IntPtr bytesWritten;
if (WriteProcessMemory(hProc, addr, newVal, 4, out bytesWritten))
Console.WriteLine($"寫入後 targetValue = {targetValue}"); // 100
CloseHandle(hProc);
Console.ReadKey();
}
[DllImport("kernel32.dll")] static extern bool CloseHandle(IntPtr hObject);
}
OpenProcess/WriteProcessMemory,違規帳號永久封鎖。本文僅供教學研究合法互操作場景使用,嚴禁用於任何未經授權的進程記憶體操作。