C# ReadProcessMemory AccessViolationException in WinForms but not in Console

174 views Asked by At

I'm writing a program which reads and writes the memory of a process. For testing purposes I wrote it first in a console application, which works; but when I moved on to a WinForms/WPF application, I get a AccessViolationException when using ReadProcessMemory from kernel32.dll.

My code:

    [DllImport("kernel32.dll")]
    public static extern int ReadProcessMemory(IntPtr Handle, long Address, byte[] buffer, int Size, int BytesRead = 0);

    ReadProcessMemory(GetProcessHandle(), Pointer, Buffer, Buffer.Length);

Why do I only get the AccessViolationException in WinForms/WPF but not in a console application, and how do I bypass this in WinForms? The error itself gives very little information to what's causing it.

0

There are 0 answers