C#拦截系统消息
首先我们看下有哪几种拦截系统消息的方法:
//一、截取系统消息
//方法一:
//添加监视消息
private void Form_Load(object sender, System.EventArgs e)
{
Application.AddMessageFilter(this);
}
//撤消消息监视
private void Form_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Application.RemoveMessageFilter(this);
}
//截取消息,进行处理
public bool PreFilterMessage(ref System.Windows.Forms.Message m)
{
switch(m.Msg )
{
case 513: //拦截左键单击事件
MessageBox.Show("哈哈,你点击了左键被拦截!");
return true; //返回true则消息被裁取,系统不再处理
case 516: //拦截左键单击事件
MessageBox.Show("哈哈,你点击了右键被拦截!");
return true; //返回true则消息被裁取,系统不再处理
default:
return false; //返回false则消息未被裁取,系统会处理
}
}
//方法二:
//截取消息,进行处理
protected override void WndProc(ref Message m)
{
switch(m.Msg)
{
case 17:
MessageBox.Show("哈哈,你不能关闭计算机!");
m.Result=(IntPtr)0;
break;
case 513:
MessageBox.Show("哈哈,你不能点击左键!");
m.Result=(IntPtr)0;
break;
case 516:
MessageBox.Show("哈哈,你不能点击右键!");
m.Result=(IntPtr)0;
break;
default:
base.WndProc(ref m);
break;
}
}
而上次写的软件用的就是第二种方法。因为习惯了,这次还是用这种方法吧。
现在我们改写这个方法,我们必须知道U盘插入拔出的系统消息。
DEVICECHANGE 0X219
DEVICEARRVIE 0X8000
DEVICEREMOVE 0X8004
我们拦截了DEVICECHANGE然后用tostring()方法:
msg=0x219 (WM_DEVICECHANGE) hwnd=0x50e54 wparam=0x8000
lparam=0x475e89c
result=0x0
也就是说,当有驱动器加载时是发送WM_DEVICECHANGE消息,但是判断驱动器是加载还是卸载就要判断WPARAM字段是DEVICEARRIVE还是DEVICEMOVE,所以我们编写如下测试代码。
程序说明:
protected override void WndProc(ref Message m)//监视Windows消息
{
const int WM_DEVICECHANGE = 0x219;
const int WM_DEVICEARRVIAL = 0x8000;//如果m.Msg的值为0x8000那么表示有U盘插入
const int WM_DEVICEMOVECOMPLETE=0x8004;
switch (m.Msg)
{
case WM_DEVICECHANGE:
{
ShowDeviceChanged("WM_DEVICECHANGE");//
if (m.WParam.ToInt32() == WM_DEVICEARRVIAL)
ShowDeviceChanged("WM_DEVICEARRVIAL");
else if (m.WParam.ToInt32() == WM_DEVICEMOVECOMPLETE)
ShowDeviceChanged("WM_DEVICEMOVECOMPLETE");
}
break;
}
base.WndProc(ref m); //将系统消息传递自父类的WndProc
}
public void ShowDeviceChanged(string message)
{
switch(message)
{
case "WM_DEVICECHANGE":
this.textBox_Message.Text += "Device Changed \r\n";
break;
case "WM_DEVICEMOVECOMPLETE":
this.textBox_Message.Text += "Device Moved\r\n";
break;
case "WM_DEVICEARRVIAL":
this.textBox_Message.Text += "Device Arrived\r\n";
break;
}
}
{
const int WM_DEVICECHANGE = 0x219;
const int WM_DEVICEARRVIAL = 0x8000;//如果m.Msg的值为0x8000那么表示有U盘插入
const int WM_DEVICEMOVECOMPLETE=0x8004;
switch (m.Msg)
{
case WM_DEVICECHANGE:
{
ShowDeviceChanged("WM_DEVICECHANGE");//
if (m.WParam.ToInt32() == WM_DEVICEARRVIAL)
ShowDeviceChanged("WM_DEVICEARRVIAL");
else if (m.WParam.ToInt32() == WM_DEVICEMOVECOMPLETE)
ShowDeviceChanged("WM_DEVICEMOVECOMPLETE");
}
break;
}
base.WndProc(ref m); //将系统消息传递自父类的WndProc
}
public void ShowDeviceChanged(string message)
{
switch(message)
{
case "WM_DEVICECHANGE":
this.textBox_Message.Text += "Device Changed \r\n";
break;
case "WM_DEVICEMOVECOMPLETE":
this.textBox_Message.Text += "Device Moved\r\n";
break;
case "WM_DEVICEARRVIAL":
this.textBox_Message.Text += "Device Arrived\r\n";
break;
}
}