C#.NET 消息机制

来源:互联网 发布:激光打标机通用软件 编辑:程序博客网 时间:2024/05/21 07:53

好文章推荐一下,转载网址:http://blog.csdn.net/fan158/article/details/6178392

 

一、消息概述 

     众人周知,window系统是一个消息驱动的系统, windows操作系统本身有自己的消息队列,消息循环,它捕捉键盘,鼠标的动作生成消息,并将这个消息传给应用程序的消息队列。 余下的工作有应用程序处理消息, windows 消息机制在这儿就不再讲述,我们重点讲述应用程序的消息机制。 大家只要明白消息是由操作系统传递给应用程序的。 一副图更能详细说明:

 

 

应用程序的执行是通过消息驱动的。消息是整个应用程序的工作引擎,我们需要理解掌握我们使用的编程语言是如何封装消息的原理。


1 什么是消息(Message) 

     消息就是通知和命令。在.NET框架类库中的System.Windows.Forms命名空间中微软采用面对对象的方式重新定义了Message。新的消息(Message)结构的公共部分属性基本与早期的一样,不过它是面对对象的。 
     公共属性: 

     HWnd     获取或设定消息的处理函数 
     Msg      获取或设定消息的ID号 
     Lparam   指定消息的LParam字段 
     Wparam   指定消息的WParam字段 
     Result   指定为响应消息处理函数而向OS系统返回的值 

2 消息驱动的过程 

     所有的外部事件,如键盘输入、鼠标移动、按动鼠标都由OS系统转换成相应的消息发送到应用程序的消息队列。每个应用程序都有一段相应的程序代码来检索、分发这些消息到对应的窗体,然后由窗体的处理函数来处理。

 

 

 

二、C#中的消息的封装 

     C#对消息重新进行了面对对象的封装,在C#中消息被封装成了事件。 
     System.Windows.Forms.Application类具有用于启动和停止应用程序和线程以及处理Windows消息的方法。 
     调用Run以启动当前线程上的应用程序消息循环,并可以选择使其窗体可见。 
     调用Exit或ExitThread来停止消息循环。 
     C#中用Application类来处理消息的接收和发送的。消息的循环是由它负责的。 
     从本质上来讲,每个窗体一般都对应一个窗体过程处理函数。那么,C#的一个Form实例(相当于一个窗体)收到消息后是如何处理消息的?其实,这个问题的分析也就是展示了C#的消息封装原理。 

     实现鼠标左键按下的消息的响应(WM_LBUTTONDOWN) 

    

 

[c-sharp] view plaincopy
  1. this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);   
  2. this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown2);   
  3.   
  4. private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)   
  5. {   
  6.   if(e.Button==System.Windows.Forms.MouseButtons.Left)   
  7.   System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown1函数响应");   
  8. }   
  9.   
  10. private void Form1_MouseDown2(object sender, System.Windows.Forms.MouseEventArgs e)   
  11. {   
  12.    if(e.Button==System.Windows.Forms.MouseButtons.Left)   
  13.    System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown2函数响应");   
  14. }   
  15.   
  16. //上面this.MouseDown是C#中的一个事件。它的定义  
  17.   
  18. public event MouseEventHandler MouseDown;   
  19. public delegate void MouseEventHandler( object sender,MouseEventArgs e); //MouseEventHandler的定义  

 

 

   实际上,上面定义了一个委托类型MouseEventHandler。委托了启用了其它编程语言中的函数指针的解决方案。与C++的函数指针不同,委托是完全面向对象的,同时封装了对象实例和方法。本质上,委托把一个实例和该实例上的方法函数封装成一个可调用的实体,它是面对对象的、安全的。 

     我们可以把 
    

 

[c-sharp] view plaincopy
  1. this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);   

    

  这条语句看成向this.MouseDown添加一个函数指针。 

     事件是对象发送的消息,以发送信号通知操作的发生。引发(触发)事件的对象叫做事件发送方。捕获事件并对事件作出响应的对象叫做事件接收方。在事件通讯中,事件发送方类并不知道哪个对象或方法将接收到(处理)它引发的事件。所需要的是在发送方和接收方之间存在一个媒介(类似指针的机制)。.NET框架定义了一个特殊的类型(Delegate委托),该类型提供函数指针的功能。这样,委托就等效于一个类型安全的函数指针或一个回调函数。 

     前面我们向this.MouseDown事件添加了两个委托。 
     

 

[c-sharp] view plaincopy
  1. this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);   
  2. this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown2);   

 

     结果,我们的两个函数Form1_MouseDown1、Form1_MouseDown2在我们单击鼠标左键的时候都会被调用,而且调用的顺序和我们添加委托的顺序一致。 

     WM_LBUTTONDOWN消息首先被Application类从应用程序消息队列中取出,然后分发到相应的窗体。窗体使用MouseDown事件中的函数指针调用已经添加的响应函数。所以C#中的事件字段实质上是一个函数指针列表,用来维护一些消息到达时的响应函数的地址。    

 

三、结论 

     C#中消息的工作流程: 

     C#中的消息被Application类从应用程序消息队列中取出,然后分发到消息对应的窗体,窗体对象的第一个响应函数是对象中的protected override void WndProc(ref System.Windows.Forms.Message e)方法。 
     它再根据消息的类型调用默认的消息响应函数(如OnMouseDown),默认的响应函数然后根据对象的事件字段(如this.MouseDown )中的函数指针列表,调用用户所加入的响应函数(如Form1_MouseDown1和Form1_MouseDown2),而且调用顺序和用户添加顺序一致。 

四、再回首Application类 

     Application类有一个AddMessageFilter的静态方法,通过它我们可以添加消息筛选器,以便在向目标传递Windows消息时,检视这些消息。 
     使用消息筛选器来防止引发特定事件,或在将某事件传递给事件处理程序之前使用消息筛选器对其执行特殊操作。我们必须提供IMessageFilter接口的一个实现,然后才可以使用消息筛选器。以下的示范代码将演示在消息发往窗体前我们如何拦截它。我们拦截的同样是WM_LBUTTONDOWN消息。 

  

 

[c-sharp] view plaincopy
  1. using System;  
  2. using System.Drawing;  
  3. using System.Collections;  
  4. using System.ComponentModel;  
  5. using System.Windows.Forms;  
  6. using System.Data;  
  7.   
  8. namespace MessageMech3  
  9. {  
  10.        
  11.     public class CLButtonDownFilter : IMessageFilter  
  12.     {//实现消息过滤器接口  
  13.         public bool PreFilterMessage(ref Message m)  
  14.         {  
  15.             if (m.Msg == 0x0201)// WM_LBUTTONDOWN   
  16.             {  
  17.                 System.Windows.Forms.MessageBox.Show("App中鼠标左键按下");  
  18.                 //返回值为true, 表示消息已被处理,不要再往后传递,因此消息被截获  
  19.   
  20.                   //返回值为false,表示消息未被处理,需要再往后传递,因此消息未被截获  
  21.   
  22.                   return true;  
  23.             }  
  24.             return false;  
  25.         }  
  26.     }  
  27.   
  28.     public class WinForm : System.Windows.Forms.Form  
  29.     {  
  30.         private System.Windows.Forms.Label label1;  
  31.         private System.ComponentModel.Container components = null;  
  32.   
  33.         public WinForm()  
  34.         {  
  35.             InitializeComponent();  
  36.   
  37.             //安装自己的过滤器  
  38.    
  39.             CLButtonDownFilter MyFilter = new CLButtonDownFilter();  
  40.             System.Windows.Forms.Application.AddMessageFilter(MyFilter);  
  41.         }  
  42.   
  43.   
  44.         protected override void Dispose(bool disposing)  
  45.         {  
  46.             if (disposing)  
  47.             {  
  48.                 if (components != null)  
  49.                 {  
  50.                     components.Dispose();  
  51.                 }  
  52.             }  
  53.             base.Dispose(disposing);  
  54.         }  
  55.  
  56.         #region Windows Form Designer generated code  
  57.         private void InitializeComponent()  
  58.         {  
  59.             this.label1 = new System.Windows.Forms.Label();  
  60.             this.SuspendLayout();  
  61.   
  62.             this.label1.BackColor = System.Drawing.Color.Transparent;  
  63.             this.label1.Dock = System.Windows.Forms.DockStyle.Top;  
  64.             this.label1.ForeColor = System.Drawing.Color.DarkViolet;  
  65.             this.label1.Name = "label1";  
  66.             this.label1.Size = new System.Drawing.Size(440, 32);  
  67.             this.label1.TabIndex = 0;  
  68.             this.label1.Text = "演示如何在App对象中处理消息,请点鼠标左键";  
  69.             this.label1.TextAlign = System.Drawing.ContentAlignment.BottomCenter;  
  70.   
  71.             this.AutoScaleBaseSize = new System.Drawing.Size(7, 22);  
  72.             this.BackColor = System.Drawing.Color.WhiteSmoke;  
  73.             this.ClientSize = new System.Drawing.Size(440, 273);  
  74.             this.Controls.AddRange(new System.Windows.Forms.Control[] { this.label1 });  
  75.             this.Font = new System.Drawing.Font("华文行楷", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));  
  76.             this.Name = "WinForm";  
  77.             this.Text = "WinForm";  
  78.   
  79.             //消息响应函数的调用顺序和添加委托的顺序一致,即:以下命令将先调用Form1_MouseDown1再调用Form1_MouseDown2,  
  80.         通过委托添加自己的鼠标按键消息响应函数1  
  81.   
  82.             this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);  
  83.               
  84.             //通过委托添加自己的鼠标按键消息响应函数2  
  85.   
  86.             this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown2);  
  87.   
  88.             this.ResumeLayout(false);  
  89.         }  
  90.         #endregion  
  91.   
  92.   
  93.         //应用程序的主入口点  
  94.   
  95.         [STAThread]  
  96.         static void Main()  
  97.         {  
  98.             Application.Run(new WinForm()); //启动当前Form线程上的应用程序消息循环  
  99.          }  
  100.   
  101.         // 通过C#提供的事件接口添加自己的鼠标按键事件的响应函数  
  102.    
  103.         private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)  
  104.         {  
  105.             if (e.Button == System.Windows.Forms.MouseButtons.Left)  
  106.                 System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown1函数响应");  
  107.   
  108.         }  
  109.         private void Form1_MouseDown2(object sender, System.Windows.Forms.MouseEventArgs e)  
  110.         {  
  111.             if (e.Button == System.Windows.Forms.MouseButtons.Left)  
  112.                 System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown2函数响应");  
  113.   
  114.         }  
  115.   
  116.         //通过覆盖基类的事件引发函数拦截消息  
  117.   
  118.         protected override void OnMouseDown(MouseEventArgs e)  
  119.         {  
  120.             if (e.Button == System.Windows.Forms.MouseButtons.Left)  
  121.                 System.Windows.Forms.MessageBox.Show("消息被OnMouseDown函数响应");  
  122.   
  123.             //如果需要截获消息,可将base.OnMouseDown(e);语句注释掉  
  124.   
  125.             base.OnMouseDown(e);  
  126.         }  
  127.   
  128.   
  129.         //通过覆盖基类的窗体函数拦截消息  
  130.   
  131.         protected override void WndProc(ref System.Windows.Forms.Message e)  
  132.         {  
  133.             //如果需要截获消息  
  134.             //if (e.Msg == 0x0201)// WM_LBUTTONDOWN  
  135.             //    System.Windows.Forms.MessageBox.Show("消息被WndProc函数响应");  
  136.             //else  
  137.             //    base.WndProc(ref e);  
  138.    
  139.             if (e.Msg == 0x0201)  
  140.                 System.Windows.Forms.MessageBox.Show("消息被WndProc函数响应");// WM_LBUTTONDOWN, 不需要截获消息则为  
  141.             base.WndProc(ref e);  
  142.         }  
  143.   
  144.     }  
  145. }  

 

 

 

   以上代码我们首先用类CLButtonDownFilter实现了IMessageFilter接口,在WinForm初始化的时候我们安装了消息筛选器。程序实际执行的时候,在点击鼠标左键的时候,程序仅仅会弹出一个"App中鼠标左键按下"的消息框。因为我们在消息发往窗体前拦截了它,所以窗体将接收不到WM_LBUTTONDOWN消息。 
     如果我们把 
              
         

 

[c-sharp] view plaincopy
  1. if(m.Msg==0x0201)// WM_LBUTTONDOWN {  
  2.     System.Windows.Forms.MessageBox.Show("App中鼠标左键按下");   
  3.     return true;   
  4. }  

     

      改成 
           

 

[c-sharp] view plaincopy
  1. if (m.Msg==0x0201)// WM_LBUTTONDOWN {   
  2.     System.Windows.Forms.MessageBox.Show("App中鼠标左键按下");   
  3.     return false;   
  4. }   

     

 

 那么,我们在Application类处理消息后,消息将继续发往窗体。窗体的函数将可以处理此消息。程序执行效果是顺序弹出5个消息框。 
     1:<<App中鼠标左键按下>> 
     2:<<消息被WndProc函数响应>> 
     3:<<消息被OnMouseDown函数响应>> 
     4:<<消息被Form1_MouseDown1函数响应>> 
     5:<<消息被Form1_MouseDown2函数响应>>

 

其实本文中已经说的挺详细的.弹出的对话框只是为了让你更直观的看出导致的结果.

 

 

 

先定义没过滤时的效果. 

 

[c-sharp] view plaincopy
  1. this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);   
  2. private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)   
  3. {   
  4. if (e.Button == System.Windows.Forms.MouseButtons.Left)   
  5. MessageBox.Show("消息被Form1_MouseDown1函数响应");   
  6. }   

 

主要有两种方法过滤实现过滤 
第一种: 

 

[c-sharp] view plaincopy
  1. protected override void WndProc(ref Message m)   
  2. {   
  3.    if (m.Msg == 0x0201)   
  4.      return;   
  5.    else   
  6.      base.WndProc(ref m);   
  7. }   

 

 

第二种 
不重写WndProc 

 

[c-sharp] view plaincopy
  1. //实现消息过滤器接口   
  2. public class CLButtonDownFilter : IMessageFilter   
  3. {   
  4. public bool PreFilterMessage(ref Message m)   
  5. {   
  6. if (m.Msg == 0x0201)// WM_LBUTTONDOWN   
  7. {   
  8.    //返回值为true, 表示消息已被处理,不要再往后传递,因此消息被截获   
  9.    //返回值为false,表示消息未被处理,需要再往后传递,因此消息未被截获   
  10.    return true;   
  11. }   
  12. return false;   
  13. }   
  14. }   
  15.   
  16. CLButtonDownFilter MyFilter = new CLButtonDownFilter();   
  17. System.Windows.Forms.Application.AddMessageFilter(MyFilter);