forked from DaxxTrias/Process.NET
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMemoryProtectionOperation.cs
More file actions
59 lines (48 loc) · 1.76 KB
/
MemoryProtectionOperation.cs
File metadata and controls
59 lines (48 loc) · 1.76 KB
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
using System;
using System.Runtime.InteropServices;
// ReSharper disable All
namespace ProcessNET.Memory
{
public enum MemoryProtectionType
{
Local,
External
}
public class MemoryProtectionOperation : IDisposable
{
private readonly IntPtr _hProcess;
private readonly int _oldProtect;
private readonly int _size;
private readonly MemoryProtectionType _type;
public readonly IntPtr Address;
public MemoryProtectionOperation(IntPtr hProcess, IntPtr address, int size, int flNewProtect)
{
_hProcess = hProcess;
Address = address;
_size = size;
_type = MemoryProtectionType.External;
VirtualProtectEx(hProcess, Address, size, flNewProtect, out _oldProtect);
}
public MemoryProtectionOperation(IntPtr address, int size, int flNewProtect)
{
Address = address;
_size = size;
_type = MemoryProtectionType.Local;
VirtualProtect(Address, size, flNewProtect, out _oldProtect);
}
public void Dispose()
{
int trash;
if (_type == MemoryProtectionType.Local)
VirtualProtectEx(_hProcess, Address, _size, _oldProtect, out trash);
else
VirtualProtect(Address, _size, _oldProtect, out trash);
}
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool VirtualProtect(IntPtr lpAddress, int dwSize, int flNewProtect,
out int lpflOldProtect);
[DllImport("kernel32.dll")]
private static extern bool VirtualProtectEx(IntPtr hProcess, IntPtr lpAddress, int dwSize, int flNewProtect,
out int lpflOldProtect);
}
}