用ImessageFilter接口實現截獲鍵盤消息
2024-07-21 02:16:21
供稿:網友
 
用imessagefilter接口實現截獲鍵盤消息
 
                    屠恩海(sunhai)
 imessagefilter 接口
 imessagefilter 接口允許應用程序在消息被調度到控件或窗體之前捕獲它。
 可以將實現 imessagefilter 接口的類添加到應用程序的消息泵中,以在消息被調度到控件或窗體之前將
它篩選出來或執行其他操作。若要將消息篩選器添加到應用程序的消息泵中,請使用 application 類中的 
addmessagefilter 方法。
 
 application.addmessagefilter 方法
 添加消息篩選器以便在向目標傳送 windows 消息時監視這些消息。
 [visual basic]
 public shared sub addmessagefilter( byval value as imessagefilter )
 參數
 value 
 您要安裝的 imessagefilter 接口的實現。 
 備注
 使用消息篩選器來防止引發特定事件,或在將某事件傳遞給事件處理程序之前使用消息篩選器對其執行特
殊操作。消息篩選器對特定線程是唯一的。
若要防止調度某消息,傳遞給該方法的 value 參數實例必須用處理該消息的代碼重寫 prefiltermessage 方法
。該方法必須返回 false。
 警告 向應用程序的消息泵添加消息篩選器會降低性能。
 示例
 [visual basic, c#, c++] 必須先提供 imessagefilter 接口的一個實現,然后才可以使用消息篩選器。
下面的類創建一個名為 testmessagefilter 的消息篩選器。此篩選器阻止與鼠標左鍵有關的所有消息。
[visual basic] 
' creates a message filter.
public class testmessagefilter
 implements imessagefilter
 public function prefiltermessage(byref m as system.windows.forms.message) _
 as boolean implements imessagefilter.prefiltermessage
 ' blocks all the messages relating to the left mouse button.
 if ((m.msg >= 513) and (m.msg <= 515)) then
 console.writeline("processing the messages : " & m.msg)
 return true
 end if
 return false
 end function
end class
 
 用esc鍵退出程序
  
  implements imessagefilter 
  private sub form1_load(byval sender as system.object, byval e as system.eventargs) handles 
mybase.load 
 'assign message to app and form 
 application.addmessagefilter(me) 
end sub 
  public function prefiltermessage(byref m as system.windows.forms.message) as boolean 
implements imessagefilter.prefiltermessage 
 
 dim keycode as keys = ctype(m.wparam.toint32(), keys) and keys.keycode 
 if keycode = keys.escape then
 end  '結束程序。我們在此可以調用各種方法、過程。
 end if
  end function