一、消息概述
Windows下應用程序的執行是通過消息驅動的。消息是整個應用程序的工作引擎,我們需要理解掌握我們使用的編程語言是如何封裝消息的原理。C#自定義消息通信往往采用事件驅動的方式實現,但有時候我們不得不采用操作系統的消息通信機制,例如在和底層語言開發的DLL交互時,是比較方便的。下面列舉了一些實現方式,供大家參考.
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)
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown2);
private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button==System.Windows.Forms.MouseButtons.Left)
System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown1函數響應");
}
private void Form1_MouseDown2(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button==System.Windows.Forms.MouseButtons.Left)
System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown2函數響應");
}
上面this.MouseDown是C#中的一個事件。它的定義如下:
public event MouseEventHandler MouseDown;
而MouseEventHandler的定義為:
public delegate void MouseEventHandler( object sender,MouseEventArgs e);
實際上,上面定義了一個委托類型MouseEventHandler。委托了啟用了其它編程語言中的函數指針的解決方案。與C++的函數指針不同,委托是完全面向對象的,同時封裝了對象實例和方法。本質上,委托把一個實例和該實例上的方法函數封裝成一個可調用的實體,它是面對對象的、安全的。
我們可以把
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);
這條語句看成向this.MouseDown添加一個函數指針。
事件是對象發送的消息,以發送信號通知操作的發生。引發(觸發)事件的對象叫做事件發送方。捕獲事件並對事件作出響應的對象叫做事件接收方。在事件通訊中,事件發送方類並不知道哪個對象或方法將接收到(處理)它引發的事件。所需要的是在發送方和接收方之間存在一個媒介(類似指針的機制)。.NET框架定義了一個特殊的類型(Delegate委托),該類型提供函數指針的功能。這樣,委托就等效於一個類型安全的函數指針或一個回調函數。
前面我們向this.MouseDown事件添加了兩個委托。
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);
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消息。
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace MessageMech3
{
//實現消息過濾器接口
public class CLButtonDownFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
if (m.Msg==0x0201)// WM_LBUTTONDOWN
{
System.Windows.Forms.MessageBox.Show("App中鼠標左鍵按下");
//返回值為true, 表示消息已被處理,不要再往后傳遞,因此消息被截獲
//返回值為false,表示消息未被處理,需要再往后傳遞,因此消息未被截獲
return true;
}
return false;
}
}
/// <summary>
/// Summary description for WinForm.
/// </summary>
public class WinForm : System.Windows.Forms.Form
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.Windows.Forms.Label label1;
private System.ComponentModel.Container components = null;
public WinForm()
{
//
// Required for Windows Form Designer support
//
InitializeComponent();
//
// TODO: Add any constructor code after InitializeComponent call
//
//安裝自己的過濾器
CLButtonDownFilter MyFilter=new CLButtonDownFilter();
System.Windows.Forms.Application.AddMessageFilter(MyFilter);
}
/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose (bool disposing)
{
if (disposing)
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.SuspendLayout();
//
// label1
//
this.label1.BackColor = System.Drawing.Color.Transparent;
this.label1.Dock = System.Windows.Forms.DockStyle.Top;
this.label1.ForeColor = System.Drawing.Color.DarkViolet;
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(440, 32);
this.label1.TabIndex = 0;
this.label1.Text = "演示如何在App對象中處理消息,請點鼠標左鍵";
this.label1.TextAlign = System.Drawing.ContentAlignment.BottomCenter;
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(7, 22);
this.BackColor = System.Drawing.Color.WhiteSmoke;
this.ClientSize = new System.Drawing.Size(440, 273);
this.Controls.AddRange(new System.Windows.Forms.Control[] {this.label1});
this.Font = new System.Drawing.Font("華文行楷", 15F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((System.Byte)(134)));
this.Name = "WinForm";
this.Text = "WinForm";
//消息響應函數的調用順序和添加委托的順序一致
//即:以下命令將先調用Form1_MouseDown1再調用Form1_MouseDown2
//通過委托添加自己的鼠標按鍵消息響應函數1
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);
//通過委托添加自己的鼠標按鍵消息響應函數2
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown2);
this.ResumeLayout(false);
}
#endregion
/// <summary>
/// 應用程序的主入口點。
/// </summary>
[STAThread]
static void Main()
{
Application.Run(new WinForm()); //啟動當前Form線程上的應用程序消息循環
}
//要點1
// 通過C#提供的事件接口添加自己的鼠標按鍵事件的響應函數
//
private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button==System.Windows.Forms.MouseButtons.Left)
System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown1函數響應");
}
private void Form1_MouseDown2(object sender, System.Windows.Forms.MouseEventArgs e)
{
if(e.Button==System.Windows.Forms.MouseButtons.Left)
System.Windows.Forms.MessageBox.Show("消息被Form1_MouseDown2函數響應");
}
//要點2
//通過覆蓋基類的事件引發函數攔截消息
//
protected override void OnMouseDown( MouseEventArgs e)
{
if(e.Button==System.Windows.Forms.MouseButtons.Left)
System.Windows.Forms.MessageBox.Show("消息被OnMouseDown函數響應");
//如果需要截獲消息,可將base.OnMouseDown(e);語句注釋掉
base.OnMouseDown(e);
}
//要點3
//通過覆蓋基類的窗體函數攔截消息
//
protected override void WndProc(ref System.Windows.Forms.Message e)
{
//如果需要截獲消息,
//if(e.Msg==0x0201)// WM_LBUTTONDOWN
// System.Windows.Forms.MessageBox.Show("消息被WndProc函數響應");
//else
// base.WndProc(ref e);
//不需要截獲消息則為
if(e.Msg==0x0201)// WM_LBUTTONDOWN
System.Windows.Forms.MessageBox.Show("消息被WndProc函數響應");
base.WndProc(ref e);
}
}
}
以上代碼我們首先用類CLButtonDownFilter實現了IMessageFilter接口,在WinForm初始化的時候我們安裝了消息篩選器。程序實際執行的時候,在點擊鼠標左鍵的時候,程序僅僅會彈出一個"App中鼠標左鍵按下"的消息框。因為我們在消息發往窗體前攔截了它,所以窗體將接收不到WM_LBUTTONDOWN消息。
如果我們把
if (m.Msg==0x0201)// WM_LBUTTONDOWN
{
System.Windows.Forms.MessageBox.Show("App中鼠標左鍵按下");
return true;
}
改成
if (m.Msg==0x0201)// WM_LBUTTONDOWN
{
System.Windows.Forms.MessageBox.Show("App中鼠標左鍵按下");
return false;
}
那么,我們在Application類處理消息后,消息將繼續發往窗體。窗體的函數將可以處理此消息。程序執行效果是順序彈出5個消息框。
1:<<App中鼠標左鍵按下>>
2:<<消息被WndProc函數響應>>
3:<<消息被OnMouseDown函數響應>>
4:<<消息被Form1_MouseDown1函數響應>>
5:<<消息被Form1_MouseDown2函數響應>>
其實本文中已經說的挺詳細的.彈出的對話框只是為了讓你更直觀的看出導致的結果.
先定義沒過濾時的效果.
this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.Form1_MouseDown1);
private void Form1_MouseDown1(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Button == System.Windows.Forms.MouseButtons.Left)
MessageBox.Show("消息被Form1_MouseDown1函數響應");
}
主要有兩種方法過濾實現過濾
第一種:
protected override void WndProc(ref Message m)
{
if (m.Msg == 0x0201)
return;
else
base.WndProc(ref m);
}
第二種
不重寫WndProc
//實現消息過濾器接口
public class CLButtonDownFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
if (m.Msg == 0x0201)// WM_LBUTTONDOWN
{
//返回值為true,表示消息已被處理,不要再往后傳遞,因此消息被截獲
//返回值為false,表示消息未被處理,需要再往后傳遞,因此消息未被截獲
return true;
}
return false;
}
}
CLButtonDownFilter MyFilter = new CLButtonDownFilter();
System.Windows.Forms.Application.AddMessageFilter(MyFilter);
參考出處:
http://blog.sina.com.cn/s/blog_3f39ffb50100dyee.html
http://www.cnblogs.com/mymhj/archive/2012/11/14/2770552.html
http://blog.csdn.net/yuan_hs_hf/article/details/16891585
上面的對事件的編號(就是Message.Msg屬性)不清楚的,可以查看我的另外一篇文章。Message類的屬性Msg所關聯的消息ID
==================================================================================
01. PreTranslateMessage函數,常用於屏蔽MFC對話框中默認的Enter和ESC消息
函數原型:BOOL PreTranslateMessage(MSG* pMsg)
用法舉例:
BOOL CTestDlg::PreTranslateMessage(MSG* pMsg)
{
if(pMsg->message == WM_KEYDOWN){
if(pMsg->wParam == VK_ESCAPE){
return TRUE;
}
if(pMsg->wParam == VK_RETURN){
return TRUE; // 對話框內部控件不可以接收到回車消息!!
}
}
return CDialog::PreTranslateMessage(pMsg);
}
02.響應系統按鍵
if(pMsg->message==WM_SYSKEYDOWN)
{
if(pMsg->wParam==VK_MENU)
MessageBox("alt");
}
if((pMsg->wParam==VK_F9) && (GetAsyncKeyState(VK_MENU)<0))
{
MessageBox(_T("同時按下了Alt鍵和F9鍵"));
}
函數:GetAsyncKeyState()
功能:確定用戶當前是否按下了鍵盤上的一個鍵
原型:SHORT GetAsyncKeyState(int vKey);
參數:nVirtKey指出要檢查鍵的虛鍵代碼。結果的高位指出該鍵當前是否被按下(是為1,否為0)。
常用鍵的VK值:
VK_SHIFT Shift鍵
VK_LSHIFT 左Shift鍵
VK_RSHIFT 右Shift鍵
VK_CONTROL Ctrl鍵
VK_LCONTROL 左Ctrl鍵
VK_RCONTROL 右Ctril鍵
VK_MENU Alt鍵
VK_LMENU 左Alt鍵
VK_RMENU 右Alt鍵
VK_LBUTTON 鼠標左鍵
VK_RBUTTON 鼠標右鍵
另一個函數GetKeyState與GetAsyncKeyState函數不同。GetAsyncKeyState在按下某鍵的同時調用,判斷正在按下某鍵。
GetKeyState則在按過某鍵之后再調用,它返回最近的鍵盤消息從線程的隊列中移出時的鍵盤狀態,判斷剛按過了某鍵。
與RegisterHotKey()相比,GetAsyncKeyState()的優點在於可以監控鼠標按鍵,缺點是需要使用定時器。
==========================================================================
出處:http://blog.csdn.net/bookish_2010_prj/article/details/5873896