C/C++学习:键盘记录程序代码
C/C++学习:键盘记录程序代码
键盘记录程序
主程序:
就是基于对话框的框架,加个个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)
- SetKeyHook(FALSE);
- #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()
- };
- #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;
- }
|
评论暂时关闭