事件过滤器

来源:互联网 发布:如何供货给淘宝 编辑:程序博客网 时间:2024/06/03 07:33
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Windows.Forms;namespace ConsoleApplication3{    /// <summary>    /// 自定义事件过滤器    /// </summary>    class MyEventsFilter: IMessageFilter {        public Dictionary<IntPtr, string> dic = new Dictionary<IntPtr, string>();        const int WM_LBUTTONDOWN = 0x201;        const int WM_LBUTTONUP = 0x202;        public bool  PreFilterMessage(ref Message m){            //判断是哪个控件触发事件            string controlName=dic.ContainsKey(m.HWnd)?dic[m.HWnd]:"其他控件";            if(m.Msg==WM_LBUTTONDOWN){//事件类型                Console.WriteLine(controlName+ "左键点击");                return true;//过滤了            }            else if(m.Msg==WM_LBUTTONUP ){                Console.WriteLine(controlName + "左键起");//Application.RemoveMessageFilter(this);//移除过滤器                return true;            }            return false;//设置不过滤事件        }    }    class Program    {        static void Main(string[] args)        {            Form frm = new Form();            MyEventsFilter filter = new MyEventsFilter();//事件过滤器对你            Button btn1 = new Button();            frm.Controls.Add(btn1);            filter.dic.Add(btn1.Handle, "按钮");            filter.dic.Add(frm.Handle, "窗体");            frm.MouseDown += new MouseEventHandler(frm_MouseDown);            Application.AddMessageFilter(filter);            Application.Run(frm);        }        static void frm_MouseDown(object sender, MouseEventArgs e)        {            Console.WriteLine("点击事件");//因为过滤器中返回了true所以不会响应这个事件        }    }}


0 0