如何通过Hook屏蔽键盘上的某些键

解决方案 »

  1.   

    写一个回调函数,然后用SetWindowsHook( WH_KEYBOARD, proc)设置好,也可以用SetWindowsHookEx函数,参数稍微复杂一点。
      

  2.   

    建立一个dll,其代码如下:
    // keybeep.cpp : Defines the entry point for the DLL application.
    //
    #include <windows.h>
    #include "keybeep.h"static HHOOK hkb=NULL;
    HINSTANCE hMod;BOOL APIENTRY DllMain( HANDLE hModule, 
                           DWORD  ul_reason_for_call, 
                           LPVOID lpReserved
               )
    {
        switch (ul_reason_for_call)
      {
        case DLL_PROCESS_ATTACH:
          hMod = (HINSTANCE)hModule;
          break;
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
          break;
        }
        return TRUE;
    }
    /////////////////////////////////////////////////////////////////////////////
    LRESULT CALLBACK MyKeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)

      BOOL bDisableKey  = FALSE;
      switch(wParam)
      {
      // ESC
      case VK_ESCAPE:
        MessageBeep(-1);
        break;
      // F1~F12
      case VK_F1:
      case VK_F2:
      case VK_F3:
      case VK_F4:
      case VK_F5:
      case VK_F6:
      case VK_F7:
      case VK_F8:
      case VK_F9:
      case VK_F10:
      case VK_F11:
      case VK_F12:
        MessageBeep(MB_ICONHAND);
        break;
      // 0~9
      case '1':
      case '2':
      case '3':
      case '4':
      case '5':
      case '6':
      case '7':
      case '8':
      case '9':
      case '0':  case VK_NUMPAD1:
      case VK_NUMPAD2:
      case VK_NUMPAD3:
      case VK_NUMPAD4:
      case VK_NUMPAD5:
      case VK_NUMPAD6:
      case VK_NUMPAD7:
      case VK_NUMPAD8:
      case VK_NUMPAD9:
      case VK_NUMPAD0:
        MessageBeep(MB_OK);
        bDisableKey = true;
      }  if (bDisableKey)
        return 1;
      else
        return CallNextHookEx( hkb, nCode, wParam, lParam );  
    }KEYBEEP_API BOOL InstallHook()
    {
      if (hkb == 0)
        hkb=SetWindowsHookEx(WH_KEYBOARD,(HOOKPROC)MyKeyboardProc,hMod,0);
      return TRUE;}
    KEYBEEP_API BOOL UnHook()
    {     
      if (hkb)
      {
        UnhookWindowsHookEx(hkb);
        hkb = 0;
      }
      return TRUE;
    } 建立一个测试exe,代码如下:
    // testhook.cpp : Defines the entry point for the application.
    //// Windows Header Files:
    #include <windows.h>// C RunTime Header Files
    #include <stdlib.h>
    #include <malloc.h>
    #include <memory.h>
    #include <tchar.h>#include "resource.h"
    #include "keybeep.h"#define MAX_LOADSTRING 100// Global Variables:
    HINSTANCE hInst;                // current instance
    TCHAR szTitle[MAX_LOADSTRING];                // The title bar text
    TCHAR szWindowClass[MAX_LOADSTRING];                // The title bar text// Foward declarations of functions included in this code module:
    ATOM        MyRegisterClass(HINSTANCE hInstance);
    BOOL        InitInstance(HINSTANCE, int);
    LRESULT CALLBACK  WndProc(HWND, UINT, WPARAM, LPARAM);
    LRESULT CALLBACK  About(HWND, UINT, WPARAM, LPARAM);int APIENTRY WinMain(HINSTANCE hInstance,
                         HINSTANCE hPrevInstance,
                         LPSTR     lpCmdLine,
                         int       nCmdShow)
    {
      // TODO: Place code here.
      MSG msg;
      HACCEL hAccelTable;  // Initialize global strings
      LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
      LoadString(hInstance, IDC_TESTHOOK, szWindowClass, MAX_LOADSTRING);
      MyRegisterClass(hInstance);  // Perform application initialization:
      if (!InitInstance (hInstance, nCmdShow)) 
      {
        return FALSE;
      }  hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_TESTHOOK);  // Main message loop:
      while (GetMessage(&msg, NULL, 0, 0)) 
      {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) 
        {
          TranslateMessage(&msg);
          DispatchMessage(&msg);
        }
      }  return msg.wParam;
    }//
    //  FUNCTION: MyRegisterClass()
    //
    //  PURPOSE: Registers the window class.
    //
    //  COMMENTS:
    //
    //    This function and its usage is only necessary if you want this code
    //    to be compatible with Win32 systems prior to the 'RegisterClassEx'
    //    function that was added to Windows 95. It is important to call this function
    //    so that the application will get 'well formed' small icons associated
    //    with it.
    //
    ATOM MyRegisterClass(HINSTANCE hInstance)
    {
      WNDCLASSEX wcex;  wcex.cbSize = sizeof(WNDCLASSEX);   wcex.style      = CS_HREDRAW | CS_VREDRAW;
      wcex.lpfnWndProc  = (WNDPROC)WndProc;
      wcex.cbClsExtra   = 0;
      wcex.cbWndExtra   = 0;
      wcex.hInstance    = hInstance;
      wcex.hIcon      = LoadIcon(hInstance, (LPCTSTR)IDI_TESTHOOK);
      wcex.hCursor    = LoadCursor(NULL, IDC_ARROW);
      wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
      wcex.lpszMenuName = (LPCSTR)IDC_TESTHOOK;
      wcex.lpszClassName  = szWindowClass;
      wcex.hIconSm    = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);  return RegisterClassEx(&wcex);
    }//
    //   FUNCTION: InitInstance(HANDLE, int)
    //
    //   PURPOSE: Saves instance handle and creates main window
    //
    //   COMMENTS:
    //
    //        In this function, we save the instance handle in a global variable and
    //        create and display the main program window.
    //
    BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
    {
       HWND hWnd;   hInst = hInstance; // Store instance handle in our global variable   hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
          CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);   if (!hWnd)
       {
          return FALSE;
       }   ShowWindow(hWnd, nCmdShow);
       UpdateWindow(hWnd);   return TRUE;
    }
      

  3.   

    <继续>//
    //  FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
    //
    //  PURPOSE:  Processes messages for the main window.
    //
    //  WM_COMMAND  - process the application menu
    //  WM_PAINT  - Paint the main window
    //  WM_DESTROY  - post a quit message and return
    //
    //
    LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
    {
      int wmId, wmEvent;
      PAINTSTRUCT ps;
      HDC hdc;
      TCHAR szHello[MAX_LOADSTRING];
      TCHAR szInput[256];
      LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);
        switch (message) 
      {
        case WM_COMMAND:
          wmId    = LOWORD(wParam); 
          wmEvent = HIWORD(wParam); 
          // Parse the menu selections:
          switch (wmId)
          {
            case IDM_INSTALLHOOK:
               InstallHook();
               MessageBox(hWnd, "KeyBoard Hook installed!", "Hook demo", MB_OK);
               break;
            case IDM_UNINSTALLHOOK:
               UnHook();
               MessageBox(hWnd, "KeyBoard Hook uninstalled!", "Hook demo", MB_OK);
               break;
            case IDM_ABOUT:
               DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
               break;
            case IDM_EXIT:
               DestroyWindow(hWnd);
               break;
            default:
               return DefWindowProc(hWnd, message, wParam, lParam);
          }
          break;
        case WM_CHAR:
          szInput[0] = wParam;
          szInput[1] = '\0';
          MessageBox(hWnd, szInput, "Key Pressed", MB_OK);
          break;    case WM_PAINT:
          hdc = BeginPaint(hWnd, &ps);
          // TODO: Add any drawing code here...
          RECT rt;
          GetClientRect(hWnd, &rt);
          DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
          EndPaint(hWnd, &ps);
          break;
        case WM_DESTROY:
          UnHook();
          PostQuitMessage(0);
          break;
        default:
          return DefWindowProc(hWnd, message, wParam, lParam);
       }
       return 0;
    }// Mesage handler for about box.
    LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
    {
      switch (message)
      {
        case WM_INITDIALOG:
            return TRUE;    case WM_COMMAND:
          if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL) 
          {
            EndDialog(hDlg, LOWORD(wParam));
            return TRUE;
          }
          break;
      }
        return FALSE;
    }其用到的资源文件如下://{{NO_DEPENDENCIES}}
    // Microsoft Developer Studio generated include file.
    // Used by testhook.rc
    //
    #define IDC_MYICON                      2
    #define IDD_TESTHOOK_DIALOG             102
    #define IDD_ABOUTBOX                    103
    #define IDS_APP_TITLE                   103
    #define IDM_ABOUT                       104
    #define IDM_EXIT                        105
    #define IDS_HELLO                       106
    #define IDI_TESTHOOK                    107
    #define IDI_SMALL                       108
    #define IDC_TESTHOOK                    109
    #define IDR_MAINFRAME                   128
    #define IDM_INSTALLHOOK                 32771
    #define IDM_UNINSTALLHOOK               32772
    #define IDC_STATIC                      -1// Next default values for new objects
    // 
    #ifdef APSTUDIO_INVOKED
    #ifndef APSTUDIO_READONLY_SYMBOLS
    #define _APS_NEXT_RESOURCE_VALUE        129
    #define _APS_NEXT_COMMAND_VALUE         32773
    #define _APS_NEXT_CONTROL_VALUE         1000
    #define _APS_NEXT_SYMED_VALUE           110
    #endif
    #endif//Microsoft Developer Studio generated resource script.
    //
    #include "resource.h"#define APSTUDIO_READONLY_SYMBOLS
    /////////////////////////////////////////////////////////////////////////////
    //
    // Generated from the TEXTINCLUDE 2 resource.
    //
    #define APSTUDIO_HIDDEN_SYMBOLS
    #include "windows.h"
    #undef APSTUDIO_HIDDEN_SYMBOLS
    #include "resource.h"/////////////////////////////////////////////////////////////////////////////
    #undef APSTUDIO_READONLY_SYMBOLS/////////////////////////////////////////////////////////////////////////////
    // Chinese (P.R.C.) resources#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_CHS)
    #ifdef _WIN32
    LANGUAGE LANG_CHINESE, SUBLANG_CHINESE_SIMPLIFIED
    #pragma code_page(936)
    #endif //_WIN32/////////////////////////////////////////////////////////////////////////////
    //
    // Icon
    //// Icon with lowest ID value placed first to ensure application icon
    // remains consistent on all systems.
    IDI_TESTHOOK            ICON    DISCARDABLE     "testhook.ICO"
    IDI_SMALL               ICON    DISCARDABLE     "SMALL.ICO"/////////////////////////////////////////////////////////////////////////////
    //
    // Menu
    //IDC_TESTHOOK MENU DISCARDABLE 
    BEGIN
        POPUP "&File"
        BEGIN
            MENUITEM "E&xit",                       IDM_EXIT
        END
        POPUP "Hook"
        BEGIN
            MENUITEM "Install hook",                IDM_INSTALLHOOK
            MENUITEM "Uninstall hook",              IDM_UNINSTALLHOOK
        END
        POPUP "&Help"
        BEGIN
            MENUITEM "&About ...",                  IDM_ABOUT
        END
    END
    /////////////////////////////////////////////////////////////////////////////
    //
    // Accelerator
    //IDC_TESTHOOK ACCELERATORS MOVEABLE PURE 
    BEGIN
        "?",            IDM_ABOUT,              ASCII,  ALT
        "/",            IDM_ABOUT,              ASCII,  ALT
    END
    /////////////////////////////////////////////////////////////////////////////
    //
    // Dialog
    //IDD_ABOUTBOX DIALOG DISCARDABLE  22, 17, 230, 75
    STYLE DS_MODALFRAME | WS_CAPTION | WS_SYSMENU
    CAPTION "About"
    FONT 8, "System"
    BEGIN
        ICON            IDI_TESTHOOK,IDC_MYICON,14,9,16,16
        LTEXT           "testhook Version 1.0",IDC_STATIC,49,10,119,8,
                        SS_NOPREFIX
        LTEXT           "Copyright (C) 2003",IDC_STATIC,49,20,119,8
        DEFPUSHBUTTON   "OK",IDOK,195,6,30,11,WS_GROUP
    END
    #ifdef APSTUDIO_INVOKED
    /////////////////////////////////////////////////////////////////////////////
    //
    // TEXTINCLUDE
    //2 TEXTINCLUDE DISCARDABLE 
    BEGIN
        "#define APSTUDIO_HIDDEN_SYMBOLS\r\n"
        "#include ""windows.h""\r\n"
        "#undef APSTUDIO_HIDDEN_SYMBOLS\r\n"
        "#include ""resource.h""\r\n"
        "\0"
    END3 TEXTINCLUDE DISCARDABLE 
    BEGIN
        "\r\n"
        "\0"
    END1 TEXTINCLUDE DISCARDABLE 
    BEGIN
        "resource.h\0"
    END#endif    // APSTUDIO_INVOKED
    /////////////////////////////////////////////////////////////////////////////
    //
    // String Table
    //STRINGTABLE DISCARDABLE 
    BEGIN
        IDS_APP_TITLE           "testhook"
        IDS_HELLO               "Please Select from menu -->hook-->install hook."
        IDC_TESTHOOK            "TESTHOOK"
    END#endif    // Chinese (P.R.C.) resources
    /////////////////////////////////////////////////////////////////////////////#ifndef APSTUDIO_INVOKED
    /////////////////////////////////////////////////////////////////////////////
    //
    // Generated from the TEXTINCLUDE 3 resource.
    //
    /////////////////////////////////////////////////////////////////////////////
    #endif    // not APSTUDIO_INVOKED
      

  4.   

    我也对钩子感兴趣,不过我更喜欢勾API。