代码
using System;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
/// <summary>
/// 消息事件委托
/// </summary>
/// <param name="m">消息</param>
/// <returns>是否已被处理,是否过滤掉消息</returns>
public delegate Boolean OnMessageEventHandle(Message m);
/// <summary>
/// Window Control WbdProc Hook
/// </summary>
public class WndProcHook : NativeWindow,IDisposable
{
/// <summary>
/// 根据一个控件 创建一个Hook对象
/// </summary>
/// <param name="control"></param>
public WndProcHook(Control control)
{
if (control.IsDisposed)
{
throw new Exception("窗口对象已被销毁。");
}
if (control.IsHandleCreated)
{
base.AssignHandle(control.Handle);
}
else
{
control.HandleCreated += Control_HandleCreated;
}
control.HandleDestroyed += Control_HandleDestroyed;
}
private void Control_HandleDestroyed(object sender, EventArgs e)
{
base.ReleaseHandle();
}
private void Control_HandleCreated(object sender, EventArgs e)
{
base.AssignHandle(((Control)sender).Handle);
}
/// <summary>
/// 消息处理事件
/// </summary>
public event OnMessageEventHandle OnMessage;
[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]
protected override void WndProc(ref Message m)
{
Boolean IsHandle = false;
if (OnMessage != null)
{
IsHandle = OnMessage.Invoke(m);
}
if (!IsHandle)
{
base.WndProc(ref m);
}
}
/// <summary>
/// 对象销毁
/// </summary>
public void Dispose()
{
this.ReleaseHandle();
}
}
}
举个栗子
namespace WindowsFormsApp1
{
public partial class Form2 : Form
{
public Form2()
{
InitializeComponent();
}
private WndProcHook hookWndProc { get; set; }
private void Form2_Load(object sender, EventArgs e)
{
hookWndProc = new WndProcHook(this);
hookWndProc.OnMessage += HookWndProc_OnMessage;
}
private bool HookWndProc_OnMessage(Message m)
{
return false;
}
private void button1_Click(object sender, EventArgs e)
{
hookWndProc.Dispose();
}
}
}