SetWindowsHookEx在當前程序設定鍵盤鉤子
阿新 • • 發佈:2019-01-30
vs2010新建一個空的win32工程,工程設定在靜態庫中使用mfc
1.h//鍵入如下程式碼
#ifndef MFCTEST_HEAD #define MFCTEST_HEAD #pragma once #include <afxwin.h> #include <afxframewndex.h> #define IDC_START 1012 //按鈕定義 HHOOK g_KeyBoard=NULL; LRESULT CALLBACK KeyboardProc(int code,WPARAM wParam,LPARAM lParam); //鍵盤鉤子函式定義 class CMyApp:public CWinApp { public: //建構函式 CMyApp(); //解構函式 virtual ~CMyApp(); //過載函式 public: //初始函式 virtual BOOL InitInstance(); }; class CMyWindow : public CFrameWndEx { public: //建構函式 CMyWindow(); //解構函式 virtual ~CMyWindow(); //虛擬函式 public: //命令響應訊息 virtual BOOL OnCommand(WPARAM wParam, LPARAM lParam); //訊息對映 public: afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); DECLARE_MESSAGE_MAP() public: CButton m_button; //按鈕 }; #endif
1.cpp
#include "1.h" CMyApp myapp; //建構函式 CMyApp::CMyApp() { } //解構函式 CMyApp::~CMyApp() { } //初始函式 BOOL CMyApp::InitInstance() { m_pMainWnd = new CMyWindow(); m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); return TRUE; } //{{AFX_MSG_MAP(CFrameWndEx) BEGIN_MESSAGE_MAP(CMyWindow, CFrameWndEx) ON_WM_CREATE() END_MESSAGE_MAP() //建構函式 CMyWindow::CMyWindow() { Create(NULL, TEXT("My Window")); RECT rect={0,0,50,30}; m_button.Create(TEXT("按鈕"),WS_CHILD|WS_VISIBLE,rect,this,IDC_START); } //解構函式 CMyWindow::~CMyWindow() { if (g_KeyBoard) { UnhookWindowsHookEx(g_KeyBoard); g_KeyBoard=NULL; } } //命令響應訊息 BOOL CMyWindow::OnCommand( WPARAM wParam, LPARAM lParam ) { int wmId=LOWORD(wParam); switch (wmId) { case IDC_START: { MessageBox(TEXT("測試一下哈"),TEXT("提示"),MB_OK); return true; } break; default: return true; } return __super::OnCommand(wParam,lParam); } //建立事件 int CMyWindow::OnCreate( LPCREATESTRUCT lpCreateStruct ) { __super::OnCreate(lpCreateStruct); g_KeyBoard=SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,NULL,GetCurrentThreadId()); if (g_KeyBoard==NULL) { ASSERT(FALSE); AfxMessageBox(TEXT("設定鉤子失敗")); } return true; } //鍵盤鉤子 LRESULT CALLBACK KeyboardProc( int code,WPARAM wParam,LPARAM lParam ) { if (VK_F2==wParam && (lParam>>31&1)==1) { AfxMessageBox(TEXT("我是你的大皇冠")); return true; } else return CallNextHookEx(g_KeyBoard,code,wParam,lParam); ASSERT(FALSE); return false; }