C# 窗口过程消息处理 WndProc

(hook, removedHandler));

        }

public void RemoveHookProc(HookProc hook)

        {
            if (hooks != null)
            {
                for (int i = hooks.Count - 1; i >= 0; i--)
                {
                    if (hooks[i].Key == hook)
                    {
                        hooks[i].Value?.Invoke();
                        hooks.RemoveAt(i);
                    }
                }
            }
        }

protected override void WndProc(ref Message m)

        {
            if (hooks != null)
            {
                foreach (var hook in hooks)
                {
                    if (hook.Key(ref m)) return;
                }
                const int WM_NCDESTORY = 0x0082;
                if (m.Msg == WM_NCDESTROY) // 窗口销毁时移除所有 hook
                {
                    for (int i = hooks.Count - 1; i >= 0; i--)
                    {
                        hooks[i].Value?.Invoke();
                    }
                    hooks = null;
                }
                base.WndProc(ref m);
            }
        }
    }

///

附加消息处理过程到窗口

    /// <param name="handle"/>需要附加消息处理过程的窗口句柄
    /// <param name="hook"/>消息处理过程
    /// <param name="removedHandler"/>消息处理过程移除回调
    public static void AddHook(IntPtr handle, HookProc hook, Action removedHandler = null)
    {
        if (!(NativeWindow.FromHandle(handle) is HookWindow window))
        {
            window = new HookWindow(handle);
        }
        window.AddHookProc(hook, removedHandler);
    }

///

从窗口移除附加的消息处理过程

    /// <param name="handle"/>需要移除消息处理过程的窗口句柄
    /// <param name="hook"/>消息处理过程
    public static void RemoveHook(IntPtr handle, HookProc hook)
    {
        if (NativeWindow.FromHandle(handle) is HookWindow window)
        {
            window.RemoveHookProc(hook);
        }
    }
}

} “`