Tip from Andrew Troelsen | Posted by: Duncan Mackenzie, MSDN | Translated by Findekano
說明:文章源自C# FAQ,翻譯此文僅為個人愛好,如有錯誤敬請指點
在非託管世界,截取Win32訊息進行處理得情況非常常見,Win32訊息被使用者應用程式截取就如同在訊息佇列中被彈出一般。然而在託管WIndows Form應用程式中很少碰到這種情況。Anyway,你可以通過如下步驟來截取並處理Windows訊息。
首先,建立一個實現IMessageFilter介面的輔助類,可以通過它唯一的方法PreFilterMessage()來得到原始的WPARAM 和LPARAM 資料,即實際的message ID。下面是一個簡單樣本:
public class MyMessageFilter : IMessageFilter
{
public bool PreFilterMessage(ref Message m)
{
// Intercept the left mouse button down message.
if (m.Msg == 513)
{
MessageBox.Show("WM_LBUTTONDOWN is: " + m.Msg);
return true;
}
return false;
}
}
在主程式中用Application類型註冊該輔助類:
public class mainForm : System.Windows.Forms.Form
{
private MyMessageFilter msgFliter = new MyMessageFilter();
public mainForm()
{
// Register message filter.
Application.AddMessageFilter(msgFliter);
}
…
}
此時,訊息在送往註冊的event處理器之前將被你定製的Message Filter預先處理。可以通過Application.RemoveMessageFilter() 來刪除原來註冊的Message Filter。