C/C++学习:键盘记录程序代码


键盘记录程序

主程序:

就是基于对话框的框架,加个个OnHookKey函数,

  1. long CMainDialog::OnHookKey(WPARAM wParam, LPARAM lParam)   //处理自定义消息  
  2. {  
  3.     char szKey[80]={0};  
  4.     GetKeyNameText(lParam, szKey, 80);  
  5.     CString strItem;  
  6.     strItem.Format("按键:%s\r\n", szKey);  
  7.     CString strEdit;  
  8.     GetDlgItem(IDC_KEYMSG)->GetWindowText(strEdit);  
  9.     GetDlgItem(IDC_KEYMSG)->SetWindowTextA(strEdit+strItem);  
  10.     ::MessageBeep(MB_OK);  
  11.     return 0;  
  12. }  

在初始化时,调用DLL中的:

  1. SetKeyHook(TRUE, 0, m_hWnd)  
在析构时,调用DLL中的:
  1. SetKeyHook(FALSE);  
.cpp代码
  1. #include <afxwin.h>   
  2. #define  HM_KEY WM_USER+100   
  3. //CMyApp  
  4. class CMyApp:public CWinApp  
  5. {  
  6. public:  
  7.     BOOL InitInstance();  
  8. };  
  9.   
  10. //CMyDialog  
  11. class CMainDialog:public CDialog  
  12. {  
  13. public:  
  14.     CMainDialog(CWnd* pParentWnd = NULL);  
  15.   
  16. protected:  
  17.     virtual BOOL OnInitDialog( );  
  18.     afx_msg void OnCancel();  
  19.     afx_msg long OnHookKey(WPARAM wParam, LPARAM lParam);  //处理自定义消息的声明  
  20.   
  21.     DECLARE_MESSAGE_MAP()  
  22. };  
.h代码:
  1. #include "resource.h"   
  2. #include "KeyHookApp.h"   
  3. #include "KeyHook.h"   
  4. #pragma comment(lib,"KeyHook.lib")   
  5.   
  6. CMyApp theApp;  
  7.   
  8. BOOL CMyApp::InitInstance()  
  9. {  
  10.     CMainDialog dlg;  
  11.     m_pMainWnd = &dlg;   //给m_pMainWnd 主窗口  
  12.     dlg.DoModal();  
  13.     return FALSE; //不进入消息循环  
  14. }  
  15.   
  16.   
  17. BEGIN_MESSAGE_MAP(CMainDialog, CDialog)  
  18.     ON_MESSAGE(HM_KEY, OnHookKey) //自定义消息  
  19. END_MESSAGE_MAP()  
  20.   
  21. //CMainDialog  
  22. CMainDialog::CMainDialog(CWnd* pParentWnd):CDialog(IDD_MAIN, pParentWnd)    
  23. {    
  24.   
  25. }   
  26. BOOL CMainDialog::OnInitDialog( )  
  27. {  
  28.     CDialog::OnInitDialog();  
  29.     if (!SetKeyHook(TRUE, 0, m_hWnd))  
  30.     {  
  31.         MessageBox("安装钩子失败");  
  32.     }  
  33.       
  34.     return TRUE;  
  35. }  
  36. //处理关闭消息  
  37. void CMainDialog::OnCancel()  
  38. {  
  39.     OutputDebugString("oncancel");  
  40.     SetKeyHook(FALSE);  
  41.     CDialog::OnCancel();  
  42.     return;  
  43. }  
  44. long CMainDialog::OnHookKey(WPARAM wParam, LPARAM lParam)   //处理自定义消息  
  45. {  
  46.     char szKey[80]={0};  
  47.     GetKeyNameText(lParam, szKey, 80);  
  48.     CString strItem;  
  49.     strItem.Format("按键:%s\r\n", szKey);  
  50.     CString strEdit;  
  51.     GetDlgItem(IDC_KEYMSG)->GetWindowText(strEdit);  
  52.     GetDlgItem(IDC_KEYMSG)->SetWindowTextA(strEdit+strItem);  
  53.     ::MessageBeep(MB_OK);  
  54.     return 0;  
  55. }  
  • 1
  • 2
  • 下一页

相关内容