首先我们看下有哪几种拦截系统消息的方法:





{
Application.AddMessageFilter(this);
}


{
Application.RemoveMessageFilter(this);
}


{
switch(m.Msg )
{
case 513: //拦截左键单击事件
MessageBox.Show("哈哈,你点击了左键被拦截!");
return true; //返回true则消息被裁取,系统不再处理
case 516: //拦截左键单击事件
MessageBox.Show("哈哈,你点击了右键被拦截!");
return true; //返回true则消息被裁取,系统不再处理
default:
return false; //返回false则消息未被裁取,系统会处理
}
}



{
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,所以我们编写如下测试代码。
程序说明:

{
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
}


{
switch(message)
{
case "WM_DEVICECHANGE":
this.textBox_Message.Text += "Device Changed ";
break;
case "WM_DEVICEMOVECOMPLETE":
this.textBox_Message.Text += "Device Moved ";
break;
case "WM_DEVICEARRVIAL":
this.textBox_Message.Text += "Device Arrived ";
break;
}
}