Files
IPClab3/Services/ProcessHackerService.cs
T
2026-09-19 16:13:20 +03:00

69 lines
2.3 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace IPClab3.Services;
public partial class ProcessHackerService
{
private IntPtr _processHandle;
const int PROCESS_VM_READ = 0x0010;
const int PROCESS_VM_WRITE = 0x0020;
const int PROCESS_VM_OPERATION = 0x0008;
[LibraryImport("kernel32.dll", SetLastError = true)]
public static partial IntPtr OpenProcess(int dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, int dwProcessId);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, [Out] byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesRead);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, int dwSize, out IntPtr lpNumberOfBytesWritten);
[LibraryImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static partial bool CloseHandle(IntPtr hObject);
public int StartProcess(string target)
{
var process = Process.Start(target);
CloseHandle(_processHandle);
_processHandle = OpenProcess(process.Id);
return process.Id;
}
public int AttachProcess(int pid)
{
CloseHandle(_processHandle);
_processHandle = OpenProcess(pid);
return pid;
}
private IntPtr OpenProcess(int pid)
{
return OpenProcess(PROCESS_VM_READ | PROCESS_VM_WRITE | PROCESS_VM_OPERATION, false, pid);
}
public bool ReadMemory(IntPtr address, int size, out byte[] bytes)
{
var buffer = new byte[size];
var result = ReadProcessMemory(_processHandle, address, buffer, buffer.Length, out var bytesRead);
bytes = buffer;
return result;
}
public bool WriteMemory(IntPtr address, string newMemory)
{
var newBytes = Encoding.UTF8.GetBytes(newMemory + "\0");
var result = WriteProcessMemory(_processHandle, address, newBytes, newBytes.Length, out var bytesWritten);
return result;
}
}