事件偵測(hook)是Windows消息處理機制的一個平台,應用程式可以在上面設定子進程以監視指定視窗的某種消息,
而且所監視的視窗可以是其他進程所新增的,當消息到達後,在目標視窗處理函式之前處理它。
事件偵測機制允許應用程式截獲處理Windows消息或特定事件。
本範例透過事件偵測來遮蔽指定的系統快速鍵(如 Alt+F4 等)。
private IntPtr pKeyboardHook = IntPtr.Zero; //鍵盤事件偵測控制碼
public delegate int HookProc(int nCode, Int32 wParam, IntPtr lParam); //事件偵測委託宣告
private HookProc KeyboardHookProcedure; //鍵盤事件偵測委託範例不能省略變數
public const int idHook = 13; //底層鍵盤事件偵測
[DllImport("user32.dll",CallingConvention = CallingConvention.StdCall)] //安裝事件偵測函數
public static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr pInstance, int threadId);
[DllImport("user32.dll",CallingConvention = CallingConvention.StdCall)] //卸載事件偵測函數
public static extern bool UnhookWindowsHookEx(IntPtr pHookHandle);
private int KeyboardHookProc(int nCode, Int32 wParam, IntPtr lParam) //鍵盤事件偵測處理函數
{
KeyMSG m = (KeyMSG)Marshal.PtrToStructure(lParam, typeof(KeyMSG));
if(pKeyboardHook != IntPtr.Zero)
{
switch(((Keys)m.vkCode))
{
case Keys.LWin:
case Keys.RWin:
case Keys.Delete:
case Keys.Alt:
case Keys.Escape:
case Keys.F4:
case Keys.Control:
case Keys.Tab:
return 1;
}
}
return 0;
}
public bool InsertHook() //自訂一個安裝事件偵測的方法
{
IntPtr pIn = (IntPtr)4194304;
if(this.pKeyboardHook == IntPtr.Zero) //如果沒有安裝偵測事件
{
this.KeyboardHookProcedure = new HookProc(KeyboardHookProc);
this.pKeyboardHook = SetWindowHookEx(idHook, KeyboardHookProcedure, pIn, 0); //安裝事件偵測
if(this.pKeyboardHook == IntPtr.Zero) //如果安裝事件偵測失敗
{
this.UnInsertHook(); //卸載事件偵測
return false;
}
}
return true; //如果安裝成功則返回true
}
public bool UnInsertHook() //自訂一個卸載事件偵測的方法
{
bool result = true;
if(this.pKeyboardHook != IntPtr.Zero) //如果存在鍵盤事件偵測
{
result = (UnhookWindowsHookEx(this.pKeyboardHook) && result); //卸載事件偵測
this.pKeyboardHook = IntPtr.Zero;
}
return result;
}
沒有留言:
張貼留言