コード例 #1
0
        public byte[] ReadProcMem(IntPtr addressToRead, int lengthToRead)
        {
            var newProtect = MemoryProtectionConstants.PAGE_READWRITE;

            if (!Unmanaged.VirtualProtectEx(Proc, addressToRead, (UIntPtr)lengthToRead, newProtect,
                                            out MemoryProtectionConstants oldProtect))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new Exception(string.Format("ERROR: ReadProcMem set VirtualProtectEx error {0}", error.Message));
            }

            var buffer = new byte[lengthToRead];

            if (!Unmanaged.ReadProcessMemory(Proc, addressToRead, buffer, lengthToRead, out IntPtr bufferRead))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new Exception(string.Format("ERROR: ReadProcMem ReadProcessMemory error {0}", error.Message));
            }


            if (!Unmanaged.VirtualProtectEx(Proc, addressToRead, (UIntPtr)lengthToRead, oldProtect, out newProtect))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new Exception(string.Format("ERROR: ReadProcMem unset VirtualProtectEx error {0}", error.Message));
            }


            Unmanaged.FlushInstructionCache(Proc, addressToRead, (UIntPtr)lengthToRead);

            return(buffer);
        }
コード例 #2
0
        public int WriteProcMem(IntPtr addressToWrite, byte[] bytesToWrite)
        {
            var newProtect = MemoryProtectionConstants.PAGE_READWRITE;

            if (!Unmanaged.VirtualProtectEx(Proc, addressToWrite, (UIntPtr)bytesToWrite.Length, newProtect, out MemoryProtectionConstants oldProtect))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new Exception(string.Format("ERROR: WriteProcMem set VirtualProtectEx error {0}", error.Message));
            }

            if (!Unmanaged.WriteProcessMemory(Proc, addressToWrite, bytesToWrite, bytesToWrite.Length, out int bufferWritten))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new Exception(string.Format("ERROR: WriteProcMem WriteProcessMemory error {0}", error.Message));
            }

            if (!Unmanaged.VirtualProtectEx(Proc, addressToWrite, (UIntPtr)bytesToWrite.Length, oldProtect, out newProtect))
            {
                var error = new Win32Exception(Marshal.GetLastWin32Error());
                throw new Exception(string.Format("ERROR: WriteProcMem unset VirtualProtectEx error {0}", error.Message));
            }

            Unmanaged.FlushInstructionCache(Proc, addressToWrite, (UIntPtr)bytesToWrite.Length);

            return(bufferWritten);
        }