[C# FAQ]通過Windows Forms預先處理Win32訊息

來源:互聯網
上載者:User
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。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.