public class Helper
{
[DllImport("kernel32.dll", EntryPoint = "ReadProcessMemory")]
public static extern bool ReadProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, IntPtr lpBuffer, int nSize, IntPtr lpNumberOfBytesRead);
[DllImport("kernel32.dll", EntryPoint = "OpenProcess")]
public static extern IntPtr OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll")]
private static extern void CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", EntryPoint = "WriteProcessMemory")]
public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, int[] lpBuffer, int nSize, IntPtr lpNumberOfBytesWritten);
public static int ReadMemoryValue(int baseAddress, string processName)
{
try
{
byte[] buffer = new byte[4];
IntPtr byteAddress = Marshal.UnsafeAddrOfPinnedArrayElement(buffer, 0); //获取缓冲区地址
IntPtr hProcess = OpenProcess(0x1f0fff, false, GetPidByProcessName(processName));
ReadProcessMemory(hProcess, (IntPtr)baseAddress, byteAddress, 4, IntPtr.Zero); //将制定内存中的值读入缓冲
CloseHandle(hProcess);
return Marshal.ReadInt32(byteAddress);
}
catch
{
return 0;
}
}
public static void WriteMemory(int baseAddress, string processName, int value)
{
var hProcess = OpenProcess(0x1f0fff, false, GetPidByProcessName(processName));
WriteProcessMemory(hProcess, (IntPtr)baseAddress, new int[] { value }, 4, IntPtr.Zero);
CloseHandle(hProcess);
}
public static void KillProcessByPid(int pid)
{
var process = Process.GetProcessById(pid);
process?.Kill();
}
public static void KillProcessByWinTitle(string winTitle)
{
var processes = Process.GetProcesses();
var process = processes.FirstOrDefault(z => z.MainWindowTitle.Contains(winTitle));
process?.Kill();
}
public static void KillProcessByProcessName(string processName)
{
var processes = Process.GetProcessesByName(processName);
processes.FirstOrDefault()?.Kill();
}
public static int GetPidByWinTitle(string winTitle)
{
var processes = Process.GetProcesses();
return processes.FirstOrDefault(z => z.MainWindowTitle.Contains(winTitle))?.Id ?? 0;
}
public static int GetPidByProcessName(string processName)
{
var processes = Process.GetProcessesByName(processName);
return processes.FirstOrDefault()?.Id ?? 0;
}
}
标签:IntPtr,processName,C#,写入,int,static,内存,public,hProcess
From: https://www.cnblogs.com/fires/p/18157908