using PTMedicalInsurance.Common.WinAPI; using PTMedicalInsurance.Variables; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace PTMedicalInsurance.Common.Hook { class EventHookManger { private delegate void WinEventDelegate(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime); [DllImport("user32.dll")] private static extern IntPtr SetWinEventHook(uint eventMin, uint eventMax, IntPtr hmodWinEventProc, WinEventDelegate lpfnWinEventProc, uint idProcess, uint idThread, uint dwFlags); [DllImport("user32.dll")] private static extern bool UnhookWinEvent(IntPtr hWinEventHook); [DllImport("user32.dll", SetLastError = true)] private static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); private const uint EVENT_SYSTEM_FOREGROUND = 0x0003; private const uint WINEVENT_OUTOFCONTEXT = 0x0000; private const uint WINEVENT_SKIPOWNPROCESS = 0x0002; private const uint WINEVENT_SKIPOWNTHREAD = 0x0001; private IntPtr _winEventHookHandle; private string _targetWindowTitle; public EventHookManger(string targetWindowTitle) { _targetWindowTitle = targetWindowTitle; } public void StartMonitoring() { _winEventHookHandle = SetWinEventHook(EVENT_SYSTEM_FOREGROUND, EVENT_SYSTEM_FOREGROUND, IntPtr.Zero, new WinEventDelegate(WinEventProc), 0, 0, WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS | WINEVENT_SKIPOWNTHREAD); if (_winEventHookHandle == IntPtr.Zero) { MessageBox.Show("Failed to install hook."); return; } } public void StopMonitoring() { if (_winEventHookHandle != IntPtr.Zero) { UnhookWinEvent(_winEventHookHandle); MessageBox.Show("Stopped monitoring."); } } private void WinEventProc(IntPtr hWinEventHook, uint eventType, IntPtr hwnd, int idObject, int idChild, uint dwEventThread, uint dwmsEventTime) { int threadId = WndHelper.GetWindowThreadProcessId(hwnd, out int processId); Global.writeLog($"hwnd:{hwnd},threadID:{threadId},processId:{processId}"); StringBuilder windowTitle = new StringBuilder(256); GetWindowText(hwnd, windowTitle, windowTitle.Capacity); if (windowTitle.ToString() == _targetWindowTitle) { MessageBox.Show($"Window with title '{_targetWindowTitle}' was created or set to foreground."); } } } }