C# Memory class x86

Posts 16–30 of 31 · Page 2 of 3
Quote Originally Posted by Biesi View Post
- Do not throw exceptions of type Exception (that's considered bad practice since they're a pain in the ass to catch)
Thank you for giving me recommendations on things I can and should improve.

Only thing that didn't make total sense is what I quoted you on. "Do not throw exceptions of type Exception".

Also, I forgot to reply the other day when you made the post. :|
Quote Originally Posted by Silent View Post
Only thing that didn't make total sense is what I quoted you on. "Do not throw exceptions of type Exception".
The only way to catch exceptions of type Exception is to catch all exceptions. You should never catch general exceptions without re-throwing them. CA1031: Do not catch general exception types (this indirectly includes throwing them as it requires to catch those general exception types)

Throw exceptions as specific as possible (if required, create your own exception type) so others (and you) can catch all expected exceptions and avoid having the application enter a possibly harmful state on unexpected exceptions.
Quote Originally Posted by Biesi View Post


The only way to catch exceptions of type Exception is to catch all exceptions. You should never catch general exceptions without re-throwing them. CA1031: Do not catch general exception types (this indirectly includes throwing them as it requires to catch those general exception types)

Throw exceptions as specific as possible (if required, create your own exception type) so others (and you) can catch all expected exceptions and avoid having the application enter a possibly harmful state on unexpected exceptions.
Thanks dude C:
Quote Originally Posted by Silent View Post
Hello MPGH, Today I'm going to be uploading a basic memory class for C# that I created in my spare time.

Features:
WriteBytes
WriteByte
WriteInt
WriteString
WriteFloat
ReadBytes
ReadByte
ReadInt
ReadString
ReadString Advanced
ReadFloat
PatternScan


Source:
Code:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
 
class Memory
{
    private IntPtr pHandel = IntPtr.Zero;
    private Process attachedProcess = null;
    private byte[] buffer;
 
    public bool Open_pHandel(string processName)
    {
        Process[] proc = Process.GetProcessesByName(processName);
 
        if (proc.Length == 0)
            return false;
        else if (proc.Length > 1)
            throw new Exception("More then one process found.");
        else
        {
            attachedProcess = proc[0];
            pHandel = proc[0].Handle;
            return true;
        }
    }
 
    #region x86
    #region Write
    public bool WriteBytes(int address, byte[] value, bool virtualProtect = false)
    {
        int countOfUsed = 0;
        bool result = false;
        uint oldProtection = 0;
 
 
        if (virtualProtect)
            Win32.x86.VirtualProtectEx(pHandel, address, (uint)value.Length, 0x40, out oldProtection);
 
        result = Win32.x86.WriteProcessMemory(pHandel, address, value, (uint)value.Length, out countOfUsed);
 
        if (virtualProtect)
            Win32.x86.VirtualProtectEx(pHandel, address, (uint)value.Length, oldProtection, out oldProtection);
 
        return result;
    }
 
    public bool WriteInt(int address, int value, bool virtualProtect = false)
    {
        buffer = BitConverter.GetBytes(value);
        return WriteBytes(address, buffer, virtualProtect);
    }
 
    public bool WriteByte(int address, byte value, bool virtualProtect = false)
    {
        buffer = new byte[] { value };
        return WriteBytes(address, buffer, virtualProtect);
    }
 
    public bool WriteString(int address, string value, bool virtualProtect = false)
    {
        buffer = Encoding.ASCII.GetBytes(value);//No unicode support atm
        return WriteBytes(address, buffer, virtualProtect);
    }
 
    public bool WriteFloat(int address, float value, bool virtualProtect = false)
    {
        buffer = BitConverter.GetBytes(value);
        return WriteBytes(address, buffer, virtualProtect);
    }
    #endregion
    #region Read
    public byte[] ReadBytes(int address, int length)
    {
        byte[] readBytes = new byte[length];
        int numBytesChanged = 0;
 
        Win32.x86.ReadProcessMemory(pHandel, address, readBytes, (uint)length, out numBytesChanged);
 
        return readBytes;
    }
 
    public int ReadInt(int address)
    {
        return BitConverter.ToInt32(ReadBytes(address, 4), 0);
    }
 
    public byte ReadByte(int address)
    {
        return ReadBytes(address, 1)[0];
    }
 
    public string ReadString(int address, int length)
    {//No unicode support
        return Encoding.ASCII.GetString(ReadBytes(address, length));
    }
 
    public string ReadStringAdvanced(int address, int maxStringLength = 1000)
    {//No unicode support
        string result = null;
        byte currentByte = 0;
 
        for (int i = 0; i < maxStringLength; i++)
        {
            currentByte = ReadByte(address + i);
 
            if (currentByte == 0x00)
                break;
            else
                result += (char)currentByte;
        }
 
        return result;
    }
 
    public float ReadFloat(int address)
    {
        return BitConverter.ToSingle(ReadBytes(address, 4), 0);
    }
    #endregion
    #region Scans
    public int PatternScan(string pattern)
    {
        string[] splitPattern = pattern.Split(' ');
        bool[] indexValid = new bool[splitPattern.Length];
        byte[] indexValue = new byte[splitPattern.Length];
 
        byte tempByte = (byte)0x00;
 
        for (int i = 0; i < splitPattern.Length; i++)
        {
            indexValid[i] = !(splitPattern[i] == "??" || splitPattern[i] == "?");
            if (Byte.TryParse(splitPattern[i], out tempByte))
                indexValue[i] = tempByte;
            else
                indexValid[i] = false;
        }
 
        int startOfMemory = attachedProcess.MainModule.BaseAddress.ToInt32();
        int endOfMemory = attachedProcess.MainModule.ModuleMemorySize;
 
        for (int currentMemAddy = startOfMemory; currentMemAddy < endOfMemory; currentMemAddy++)
        {
            bool complete = false;
            for (int i = 0; i < splitPattern.Length; i++)
            {
                if (!indexValid[i])
                    continue;
 
                tempByte = ReadByte(currentMemAddy + i);
 
                if (tempByte != indexValue[i])
                    break;
 
                if (i == splitPattern.Length - 1)
                    complete = true;
 
                if (complete)
                    break;
            }
 
            if (complete)
                return currentMemAddy;
        }
 
        throw new Exception("Pattern not found!");
        return 0;
    }
    #endregion
    #endregion
 
    private static class Win32
    {
        public static class NativeMethods
        {
            #region IsWow64Process
            public static bool IsWow64Process(IntPtr handel)
            {
                bool isTarget64Bit = false;
                IsWow64Process(handel, out isTarget64Bit);
                return isTarget64Bit;
            }
 
            [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
            #endregion
        }
 
        public static class x64
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern bool VirtualProtectEx(IntPtr hProcess, long lpAddress, UInt32 dwSize, uint flNewProtect, out uint lpflOldProtect);
 
            [DllImport("kernel32.dll")]
            public static extern bool ReadProcessMemory(IntPtr hProcess, long lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
 
            [DllImport("kernel32.dll")]
            public static extern bool WriteProcessMemory(IntPtr hProcess, long lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
        }
 
        public static class x86
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern bool VirtualProtectEx(IntPtr hProcess, int lpAddress, UInt32 dwSize, uint flNewProtect, out uint lpflOldProtect);
 
            [DllImport("kernel32.dll")]
            public static extern bool ReadProcessMemory(IntPtr hProcess, int lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
 
            [DllImport("kernel32.dll")]
            public static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
        }
    }
}
usage:
Code:
if(Open_pHandel("processName"))
{
     int address = PatternScan("02 255 12 41 ?? 54 ? 12 ? 52 ?? 23");
     WriteBytes(address, new byte[] {0x00, 0x00});
}
Midway typing this I noticed I left the gas on, on the stove and I got a massive headache xd whoops

Features I will add later:
x64 support.
idk what else


Press thanks if this helps you!
Thanks for this! good resource.
I don't wanna bump this thread (it already has been but whatever) but thank you so much, I had trouble with writing the address for enabling/disabling FX in mw3, this class is soooo gud for noobs, thx a lot :P
ew this code is disgusting
Quote Originally Posted by Silent View Post
ew this code is disgusting
Oh well... Kinda, yeah, but I still like it. Btw, I have a problem. I tried to read the value of the address and then change it to 5 (so when u disable the hack it wont be 5, it will be the original value, for example, 2) and when I disable the hack, I would write to the same address the original value I had before, but it doesn't work at all. Any help? Lmao:
Code:
        private void checkBox18_CheckedChanged(object sender, EventArgs e)
        {
            if (Open_pHandel("iw5sp"))
            {
                int original = ReadInt(0x012AA9A8);
                if (checkBox18.Checked == true)
                {
                    for (;;)
                    {
                        WriteInt(0x012AA9A8, 5);
                    }
                }
                else
                {
                    WriteInt(0x012AA9A8, original);
                }
            }
            else
            {
                MessageBox.Show("iw5sp.exe has not been found. Open the game first, then the trainer!", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Am I not using ReadInt correctly?

EDIT: And how do I allocate ram? I need to allocate ram in order to make my cheat work, else it would crash (OllyDBG says "access violation when executing", and I saw the cheat engine lua script which allocates ram. So how do I do that in C#?
Quote Originally Posted by EricModer13 View Post
Oh well... Kinda, yeah, but I still like it. Btw, I have a problem. I tried to read the value of the address and then change it to 5 (so when u disable the hack it wont be 5, it will be the original value, for example, 2) and when I disable the hack, I would write to the same address the original value I had before, but it doesn't work at all. Any help? Lmao:
Code:
        private void checkBox18_CheckedChanged(object sender, EventArgs e)
        {
            if (Open_pHandel("iw5sp"))
            {
                int original = ReadInt(0x012AA9A8);
                if (checkBox18.Checked == true)
                {
                    for (;;)
                    {
                        WriteInt(0x012AA9A8, 5);
                    }
                }
                else
                {
                    WriteInt(0x012AA9A8, original);
                }
            }
            else
            {
                MessageBox.Show("iw5sp.exe has not been found. Open the game first, then the trainer!", "Error",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Am I not using ReadInt correctly?

EDIT: And how do I allocate ram? I need to allocate ram in order to make my cheat work, else it would crash (OllyDBG says "access violation when executing", and I saw the cheat engine lua script which allocates ram. So how do I do that in C#?
Code:
                    for (;;)
                    {
                        WriteInt(0x012AA9A8, 5);
                    }
Gets you stuck in an infinite loop in the UI thread. So toggle off is no longer an option. Run this in a separate thread, and check the checkbox state on each iteration of the loop.
Quote Originally Posted by Hell_Demon View Post
Code:
                    for (;;)
                    {
                        WriteInt(0x012AA9A8, 5);
                    }
Gets you stuck in an infinite loop in the UI thread. So toggle off is no longer an option. Run this in a separate thread, and check the checkbox state on each iteration of the loop.
inb4:

Code:
for(;;) {
     new Thread(delegate() {
          WriteInt(0x0000, 5);
     }).Start();
}
Quote Originally Posted by Hell_Demon View Post
Code:
                    for (;;)
                    {
                        WriteInt(0x012AA9A8, 5);
                    }
Gets you stuck in an infinite loop in the UI thread. So toggle off is no longer an option. Run this in a separate thread, and check the checkbox state on each iteration of the loop.
Well, I know the UI freezes, I've fixed that later myself with the same thing u mentioned to me.
Quote Originally Posted by Silent View Post
Hello MPGH, Today I'm going to be uploading a basic memory class for C# that I created in my spare time.

Features:
WriteBytes
WriteByte
WriteInt
WriteString
WriteFloat
ReadBytes
ReadByte
ReadInt
ReadString
ReadString Advanced
ReadFloat
PatternScan


Source:
Code:
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
 
class Memory
{
    private IntPtr pHandel = IntPtr.Zero;
    private Process attachedProcess = null;
    private byte[] buffer;
 
    public bool Open_pHandel(string processName)
    {
        Process[] proc = Process.GetProcessesByName(processName);
 
        if (proc.Length == 0)
            return false;
        else if (proc.Length > 1)
            throw new Exception("More then one process found.");
        else
        {
            attachedProcess = proc[0];
            pHandel = proc[0].Handle;
            return true;
        }
    }
 
    #region x86
    #region Write
    public bool WriteBytes(int address, byte[] value, bool virtualProtect = false)
    {
        int countOfUsed = 0;
        bool result = false;
        uint oldProtection = 0;
 
 
        if (virtualProtect)
            Win32.x86.VirtualProtectEx(pHandel, address, (uint)value.Length, 0x40, out oldProtection);
 
        result = Win32.x86.WriteProcessMemory(pHandel, address, value, (uint)value.Length, out countOfUsed);
 
        if (virtualProtect)
            Win32.x86.VirtualProtectEx(pHandel, address, (uint)value.Length, oldProtection, out oldProtection);
 
        return result;
    }
 
    public bool WriteInt(int address, int value, bool virtualProtect = false)
    {
        buffer = BitConverter.GetBytes(value);
        return WriteBytes(address, buffer, virtualProtect);
    }
 
    public bool WriteByte(int address, byte value, bool virtualProtect = false)
    {
        buffer = new byte[] { value };
        return WriteBytes(address, buffer, virtualProtect);
    }
 
    public bool WriteString(int address, string value, bool virtualProtect = false)
    {
        buffer = Encoding.ASCII.GetBytes(value);//No unicode support atm
        return WriteBytes(address, buffer, virtualProtect);
    }
 
    public bool WriteFloat(int address, float value, bool virtualProtect = false)
    {
        buffer = BitConverter.GetBytes(value);
        return WriteBytes(address, buffer, virtualProtect);
    }
    #endregion
    #region Read
    public byte[] ReadBytes(int address, int length)
    {
        byte[] readBytes = new byte[length];
        int numBytesChanged = 0;
 
        Win32.x86.ReadProcessMemory(pHandel, address, readBytes, (uint)length, out numBytesChanged);
 
        return readBytes;
    }
 
    public int ReadInt(int address)
    {
        return BitConverter.ToInt32(ReadBytes(address, 4), 0);
    }
 
    public byte ReadByte(int address)
    {
        return ReadBytes(address, 1)[0];
    }
 
    public string ReadString(int address, int length)
    {//No unicode support
        return Encoding.ASCII.GetString(ReadBytes(address, length));
    }
 
    public string ReadStringAdvanced(int address, int maxStringLength = 1000)
    {//No unicode support
        string result = null;
        byte currentByte = 0;
 
        for (int i = 0; i < maxStringLength; i++)
        {
            currentByte = ReadByte(address + i);
 
            if (currentByte == 0x00)
                break;
            else
                result += (char)currentByte;
        }
 
        return result;
    }
 
    public float ReadFloat(int address)
    {
        return BitConverter.ToSingle(ReadBytes(address, 4), 0);
    }
    #endregion
    #region Scans
    public int PatternScan(string pattern)
    {
        string[] splitPattern = pattern.Split(' ');
        bool[] indexValid = new bool[splitPattern.Length];
        byte[] indexValue = new byte[splitPattern.Length];
 
        byte tempByte = (byte)0x00;
 
        for (int i = 0; i < splitPattern.Length; i++)
        {
            indexValid[i] = !(splitPattern[i] == "??" || splitPattern[i] == "?");
            if (Byte.TryParse(splitPattern[i], out tempByte))
                indexValue[i] = tempByte;
            else
                indexValid[i] = false;
        }
 
        int startOfMemory = attachedProcess.MainModule.BaseAddress.ToInt32();
        int endOfMemory = attachedProcess.MainModule.ModuleMemorySize;
 
        for (int currentMemAddy = startOfMemory; currentMemAddy < endOfMemory; currentMemAddy++)
        {
            bool complete = false;
            for (int i = 0; i < splitPattern.Length; i++)
            {
                if (!indexValid[i])
                    continue;
 
                tempByte = ReadByte(currentMemAddy + i);
 
                if (tempByte != indexValue[i])
                    break;
 
                if (i == splitPattern.Length - 1)
                    complete = true;
 
                if (complete)
                    break;
            }
 
            if (complete)
                return currentMemAddy;
        }
 
        throw new Exception("Pattern not found!");
        return 0;
    }
    #endregion
    #endregion
 
    private static class Win32
    {
        public static class NativeMethods
        {
            #region IsWow64Process
            public static bool IsWow64Process(IntPtr handel)
            {
                bool isTarget64Bit = false;
                IsWow64Process(handel, out isTarget64Bit);
                return isTarget64Bit;
            }
 
            [DllImport("kernel32.dll", SetLastError = true, CallingConvention = CallingConvention.Winapi)]
            [return: MarshalAs(UnmanagedType.Bool)]
            private static extern bool IsWow64Process([In] IntPtr process, [Out] out bool wow64Process);
            #endregion
        }
 
        public static class x64
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern bool VirtualProtectEx(IntPtr hProcess, long lpAddress, UInt32 dwSize, uint flNewProtect, out uint lpflOldProtect);
 
            [DllImport("kernel32.dll")]
            public static extern bool ReadProcessMemory(IntPtr hProcess, long lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
 
            [DllImport("kernel32.dll")]
            public static extern bool WriteProcessMemory(IntPtr hProcess, long lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
        }
 
        public static class x86
        {
            [DllImport("kernel32.dll", SetLastError = true)]
            public static extern bool VirtualProtectEx(IntPtr hProcess, int lpAddress, UInt32 dwSize, uint flNewProtect, out uint lpflOldProtect);
 
            [DllImport("kernel32.dll")]
            public static extern bool ReadProcessMemory(IntPtr hProcess, int lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
 
            [DllImport("kernel32.dll")]
            public static extern bool WriteProcessMemory(IntPtr hProcess, int lpBaseAddress, [In, Out] byte[] buffer, UInt32 size, out int lpNumberOfBytesWritten);
        }
    }
}
usage:
Code:
if(Open_pHandel("processName"))
{
     int address = PatternScan("02 255 12 41 ?? 54 ? 12 ? 52 ?? 23");
     WriteBytes(address, new byte[] {0x00, 0x00});
}
Midway typing this I noticed I left the gas on, on the stove and I got a massive headache xd whoops

Features I will add later:
x64 support.
idk what else


Press thanks if this helps you!
Waiting for x64
Quote Originally Posted by mjts140914 View Post
Waiting for x64
eh, why not. I'll do it now. NodeJS is pissing me off, wouldn't mind going to C# for 10 minutes.

edit: nevermind, forgot how much cancer statically-typed languages are.
Quote Originally Posted by Silent View Post
edit: nevermind, forgot how much cancer statically-typed languages are.
Code:
UIntPtr
might be the help for all of your problems. No need to dynamically switch between x64 and x86
Wait, did Silent just get banned? xd
Quote Originally Posted by EricModer13 View Post
Wait, did Silent just get banned? xd
no????????????????????????????????????
Posts 16–30 of 31 · Page 2 of 3

Post a Reply

Similar Threads

Tags for this Thread

None

Talk with us