0

I know everything about process and what address i want to read, but i don't know how to use Readprocessmemory function. Do i need to add some usings or something? I made this in C++, but how can i do it in C#?

    char* ReadMemoryText(DWORD address,int size)
    {
        char ret[size];
        DWORD processId;
        HWND hwnd = FindWindow("WindowX",NULL);
        if(tibia!=NULL)
        {
            GetWindowThreadProcessId(hwnd,&processId);
            HANDLE phandle = OpenProcess(PROCESS_VM_READ, 0, processId);
            if(!phandle)
            {
                cout<<GetLastError()<<endl;
                cout <<"Could not get handle!\n";
                cin.get();
            }
            ReadProcessMemory(phandle, (LPVOID)address, &ret,size,0);
            char * rt = ret;
            for(int i=0;i<size && ret[i]!=0;++i)
                cout << ret[i];
            return rt;
        }
        return NULL;
    }
Matt
  • 22,721
  • 17
  • 71
  • 112
Piotr Łużecki
  • 1,031
  • 4
  • 17
  • 33
  • possible duplicate of [Convert ReadProcessMemory output to string](http://stackoverflow.com/questions/3131733/convert-readprocessmemory-output-to-string) – Hans Passant Apr 29 '12 at 20:51
  • 1
    [Stack Overflow is not a code translation service](http://meta.stackexchange.com/a/129362/172141) – L.B Apr 29 '12 at 20:59

1 Answers1

0

Here is an example of using C# that reads a char array from memory. In this case it's the local player's name string from Assault Cube.

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ReadProcessMemory(
IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, Int32 nSize, out IntPtr lpNumberOfBytesRead);

var nameAddr = ghapi.FindDMAAddy(hProc, (IntPtr)(modBase2 + 0x10f4f4), new int[] { 0x225 });

byte[] name = new byte[16];

ghapi.ReadProcessMemory(hProc, nameAddr, name, 16, out _);

Console.WriteLine(Encoding.Default.GetString(name));

We use pinvoke to get access to ReadProcessMemory exported from kernel32.dll

We use FindDMAAddy to get the address of the name variable. The char array is a fixed size of 16 bytes.

We use ReadProcessMemory using source and destination variables, size 16 and the last argument we just use "out _" because we don't care about bytesRead argument.

Then we need to convert that char array to a string type with proper encoding for which we use Encoding.Default.GetString().

Then write that line to the console.

GuidedHacking
  • 3,628
  • 1
  • 9
  • 59