HookImpl
今天试着写了一个HOOKIMPL WTL用的,感觉还好..就是只能单实例...以后再加
1 #pragma once 2 3 template <typename T> 4 class ATL_NO_VTABLE CHookImpl 5 { 6 UINT WM_HOOKIMPL; 7 HHOOK m_hHook; 8 static T* m_pT; 9 public: 10 CHookImpl( UINT nMsgHook = WM_USER + 0x3000 ) : WM_HOOKIMPL( nMsgHook ), m_hHook( NULL ) 11 { 12 m_pT = static_cast<T*>( this ); 13 } 14 15 ~CHookImpl() 16 { 17 if ( m_hHook ) 18 { 19 ::UnhookWindowsHookEx( m_hHook ); 20 } 21 } 22 23 bool InstallHook( int nHookType ) 24 { 25 if ( m_hHook ) 26 { 27 if ( !::UnhookWindowsHookEx( m_hHook ) ) 28 { 29 return false; 30 } 31 } 32 33 m_hHook = ::SetWindowsHookEx( nHookType, _FunHookProc, ModuleHelper::GetModuleInstance(), 0 ); 34 35 return m_hHook != NULL; 36 } 37 38 bool RemoveHook() 39 { 40 if ( m_hHook && ::UnhookWindowsHookEx( m_hHook ) ) 41 { 42 m_hHook = NULL; 43 return true; 44 } 45 46 return false; 47 } 48 49 static LRESULT CALLBACK _FunHookProc( int nCode, WPARAM wParam, LPARAM lParam ) 50 { 51 LRESULT lRet; 52 53 lRet = ::CallNextHookEx( m_pT->m_hHook, nCode, wParam, lParam ); 54 55 if ( nCode == HC_ACTION ) 56 { 57 ::SendMessage( m_pT->m_hWnd, m_pT->WM_HOOKIMPL, wParam, lParam ); 58 } 59 60 return lRet; 61 } 62 63 64 BEGIN_MSG_MAP( CHookImpl<T> ) 65 MESSAGE_HANDLER( WM_HOOKIMPL, OnHookAction ) 66 END_MSG_MAP() 67 68 69 LRESULT OnHookAction( UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled ) 70 { 71 m_pT->HookAction( wParam, lParam ); 72 bHandled = TRUE; 73 return 0; 74 } 75 76 void HookAction( WPARAM /*wParam*/, LPARAM /*lParam*/ ) 77 { 78 ATLASSERT( FALSE ); 79 } 80 }; 81 82 template<typename T> 83 T* CHookImpl<T>::m_pT = NULL;