2
0

ProcessHelper.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Net.NetworkInformation;
  7. using System.Runtime.InteropServices;
  8. using System.Text;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. namespace WechatBakTool.Helpers
  12. {
  13. public class ProcessHelper
  14. {
  15. public static ProcessModule? FindProcessModule(int ProcessId, string ModuleName)
  16. {
  17. Process process = Process.GetProcessById(ProcessId);
  18. foreach (ProcessModule module in process.Modules)
  19. {
  20. if (module.ModuleName == ModuleName)
  21. return module;
  22. }
  23. return null;
  24. }
  25. public static List<int> FindProcessMemory(IntPtr processHandle, ProcessModule module, string content)
  26. {
  27. byte[] buffer = new byte[module.ModuleMemorySize];
  28. byte[] search = Encoding.ASCII.GetBytes(content);
  29. // 逐页读取数据
  30. List<int> offset = new List<int>();
  31. int readBytes;
  32. bool success = NativeAPI.ReadProcessMemory(processHandle, module.BaseAddress, buffer, buffer.Length,out readBytes);
  33. if (!success || readBytes == 0)
  34. {
  35. int error = Marshal.GetLastWin32Error();
  36. Console.WriteLine($"ReadProcessMemory failed. GetLastError: {error}");
  37. }
  38. else
  39. {
  40. for (int i = 0; i < buffer.Length; i++)
  41. {
  42. if (buffer[i] == search[0])
  43. {
  44. for (int s = 1; s < search.Length; s++)
  45. {
  46. if (buffer[i + s] != search[s])
  47. break;
  48. if (s == search.Length - 1)
  49. offset.Add(i);
  50. }
  51. }
  52. }
  53. }
  54. return offset;
  55. }
  56. // 这里开始下面是对Windows API引用声明
  57. public static byte[]? ReadMemoryDate(IntPtr hProcess, IntPtr lpBaseAddress, int nSize = 100)
  58. {
  59. byte[] array = new byte[nSize];
  60. int readByte;
  61. if (!NativeAPI.ReadProcessMemory(hProcess, lpBaseAddress, array, nSize, out readByte))
  62. return null;
  63. else
  64. return array;
  65. }
  66. }
  67. }