您的位置:首页 > 编程语言 > C#

C# 怎样截取系统向应用程序发送的消息

2013-07-23 10:51 239 查看
众所周知,windows会为每一个应用程序创建一个消息队列,通过向应用程序发送消息告知应用程序用户做了哪些操作,那么如果我想截取这些消息进行重定义,该怎么做呢?

这里有两种方法:

1.重写窗体的WndProc方法,实现如下:

public partial class Form5 : Form
{
public Form5()
{
InitializeComponent();
}

protected override void WndProc(ref Message m)//重写继承的WndProc方法
{
switch (m.Msg)
{
case 513:                             //513代表windo向窗体发送的单击鼠标左键的消息值
MessageBox.Show("单击了鼠标左键");
m.Result = (IntPtr)0;
break;
case 516:
MessageBox.Show("单击了鼠标右键");
m.Result = (IntPtr)0;
break;
default:
base.WndProc(ref m);             //其他操作交由基础类进行默认处理
break;
}
}
}


2.使用ImessageFilter接口

MSDN上对ImessageFilter的定义如下:

此接口允许应用程序在消息被调度到控件或窗体之前捕获它。

可以将实现 IMessageFilter 接口的类添加到应用程序的消息泵中,以在消息被调度到控件或窗体之前将它筛选出来或执行其他操作。若要将消息筛选器添加到应用程序的消息泵中,请使用Application
类中的AddMessageFilter
方法。

具体实现方法如下:

public partial class Form5 : Form
{
MessageFilter myMessage = new MessageFilter();//定义新的MessageFilter对象
public Form5()
{
InitializeComponent();
}

private void Form5_Load(object sender, EventArgs e)
{
Application.AddMessageFilter(myMessage);//将新的MessageFilter对象添加到应用程序中
}
}

public class MessageFilter:IMessageFilter     //继承自IMessageFilter接口
{
public bool PreFilterMessage(ref Message m)
{
switch (m.Msg)
{
case 513:
MessageBox.Show("单击了鼠标左键");
return true;
case 516:
MessageBox.Show("单击了鼠标右键");
return true;
default:
return false;

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: