-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMemory.cs
81 lines (72 loc) · 2.75 KB
/
Memory.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace cs2
{
internal static class Memory
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out][MarshalAs(UnmanagedType.AsAny)] object lpBuffer, int dwSize, out int lpNumberOfBytesRead);
public static bool Initialize(out string mes)
{
mes = "The program is already running";
if (Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName).Length > 1)
return false;
mes = "CS2 process not found";
var procList = Process.GetProcessesByName("cs2");
if (procList.Length == 0)
return false;
_proc = procList[0];
foreach(ProcessModule module in _proc.Modules)
{
try
{
if (module.ModuleName == "client.dll")
{
ClientPtr = module.BaseAddress;
return true;
}
}
catch { };
}
throw new DllNotFoundException("client.dll");
}
public static T Read<T>(IntPtr Address) where T : unmanaged
{
var size = Marshal.SizeOf<T>();
var buffer = default(T) as object;
ReadProcessMemory(_proc.Handle, Address, buffer, size, out var lpNumberOfBytesRead);
return lpNumberOfBytesRead == size ? (T)buffer : default;
}
public static byte[] ReadBytes(IntPtr hProcess, IntPtr lpBaseAddress, int maxLength)
{
var buffer = new byte[maxLength];
ReadProcessMemory(hProcess, lpBaseAddress, buffer, maxLength, out _);
return buffer;
}
public static byte[] ReadBytes(IntPtr lpBaseAddress, int maxLength)
{
var buffer = new byte[maxLength];
ReadProcessMemory(_proc.Handle, lpBaseAddress, buffer, maxLength, out _);
return buffer;
}
public static string ReadString(IntPtr lpBaseAddress, int maxLength = 256)
{
var buffer = ReadBytes(_proc.Handle, lpBaseAddress, maxLength);
var nullCharIndex = Array.IndexOf(buffer, (byte)'\0');
return nullCharIndex >= 0
? Encoding.UTF8.GetString(buffer, 0, nullCharIndex).Trim()
: Encoding.UTF8.GetString(buffer).Trim();
}
public static IntPtr ClientPtr
{
get; set;
}
private static Process _proc = null!;
}
}