EventHookManger.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. using PTMedicalInsurance.Common.WinAPI;
  2. using PTMedicalInsurance.Variables;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Runtime.InteropServices;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace PTMedicalInsurance.Common.Hook
  11. {
  12. class EventHookManger
  13. {
  14. private delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime);
  15. [DllImport("user32.dll")]
  16. private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags);
  17. [DllImport("user32.dll")]
  18. private static extern bool UnhookWinEvent(IntPtr hWinEventHook);
  19. [DllImport("user32.dll", SetLastError = true)]
  20. private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
  21. private const uint EVENT_SYSTEM_FOREGROUND = 0x0003;
  22. private const uint WINEVENT_OUTOFCONTEXT = 0x0000;
  23. private const uint WINEVENT_SKIPOWNPROCESS = 0x0002;
  24. private const uint WINEVENT_SKIPOWNTHREAD = 0x0001;
  25. private IntPtr _winEventHookHandle;
  26. private string _targetWindowTitle;
  27. public EventHookManger(string targetWindowTitle)
  28. {
  29. _targetWindowTitle = targetWindowTitle;
  30. }
  31. public void StartMonitoring()
  32. {
  33. _winEventHookHandle = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, new WinEventDelegate(WinEventProc), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS | WINEVENT_SKIPOWNTHREAD);
  34. if (_winEventHookHandle == IntPtr.Zero)
  35. {
  36. MessageBox.Show("Failed to install hook.");
  37. return;
  38. }
  39. }
  40. public void StopMonitoring()
  41. {
  42. if (_winEventHookHandle != IntPtr.Zero)
  43. {
  44. UnhookWinEvent(_winEventHookHandle);
  45. MessageBox.Show("Stopped monitoring.");
  46. }
  47. }
  48. private void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime)
  49. {
  50. int threadId = WndHelper.GetWindowThreadProcessId(hwnd, out int processId);
  51. Global.writeLog($"hwnd:{hwnd},threadID:{threadId},processId:{processId}");
  52. StringBuilder windowTitle = new StringBuilder(256);
  53. GetWindowText(hwnd, windowTitle, windowTitle.Capacity);
  54. if (windowTitle.ToString() == _targetWindowTitle)
  55. {
  56. MessageBox.Show($"Window with title '{_targetWindowTitle}' was created or set to foreground.");
  57. }
  58. }
  59. }
  60. }