方法一:使用钩子
首先在api声明的类里声明委托
public delegate int procEntry(int nCode, int wParam, IntPtr lParam);
截取鼠标消息关键代码:
private IntPtr hand;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public int myMouse(int nCode, Int32 wParam, IntPtr IParam)
{
if (nCode>=0)
{
switch(wParam)
{
case APIMessage.WM_RBUTTONDOWN:
MessageBox.Show("hello");
break;
}
}
return (int)API.CallNextHookEx(hand, nCode, wParam, IParam);
}
private void button1_Click(object sender, EventArgs e)
{
// int m = API.GetCurrentThreadId();
hand =(IntPtr)API.SetWindowsHookEx(HookType: 14, methodAddress: myMouse, handler: IntPtr.Zero, dwThread: 0);
// int n=Marshal.GetLastWin32Error();
// string mes = new System.ComponentModel.Win32Exception(n).Message;
}
private void button2_Click(object sender, EventArgs e)
{
API.UnhookWindowsHookEx(hand);
}
截取键盘消息关键代码:
/// <summary>
/// 键盘事件结构体
/// </summary>
[StructLayout(LayoutKind.Sequential)]
public struct KeyMSG
{
public int vkCode;//按键
public int scanCode;
public int flags;//标志是keyDown或keyUp
public int time;
public int dwExtraInfo;
}
hand=myhook.SetWindowsHookEx(13, new myhook.procEntry(mykey), IntPtr.Zero, 0);
//由于是hook键盘事件,因此只能声明全局钩子
//处理函数,将lparam中的数据用KeyMSG结构体取出来,并交给专门的键盘事件处理函数,这里的返回值应为0,以保证消息的传递不被中断。
private int mykey(int nCode, int wParam, IntPtr lParam)
{
if (nCode>=0)
{
KeyMSG mykey =(KeyMSG)Marshal.PtrToStructure(lParam, typeof(KeyMSG));
if (mykey.flags==0)
{
KeyEventArgs e = new KeyEventArgs((Keys)mykey.vkCode);
mykeyfunc(this, e);
}
myhook.CallNextHookEx((IntPtr)hand, nCode, wParam, lParam);
}
return 0;
}
//键盘事件处理函数
private void mykeyfunc(object sender, KeyEventArgs e){
textBox2.Text += e.KeyData;
}
方法二:
在winForm中截取系统消息,此处有两个方案(以截取鼠标事件为例)
方案一:通过实现IMessageFilter接口来创建消息筛选器,从而截取windows消息
关键代码:
筛选器:
public class myMessage : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
switch (m.Msg)
{
case 513:
MessageBox.Show("左键");
break;
}
return false;
}
}
若返回值为true则可使消息传递中断添加筛选器:
Application.AddMessageFilter(new myMessage());
方案二:在Form中重写Control类虚方法WndProc来截取Windows消息
关键代码:
protected override void WndProc(ref Message m)
当处理完消息后,应调用base.WndProc(ref m)使消息继续传递下去