龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 软件开发 > C/C++开发 >

C++键盘记录程序代码

时间:2014-10-17 02:10来源:网络整理 作者:网络 点击:
分享到:
这篇文章主要介绍了C++键盘记录程序代码,是Windows应用程序开发中非常实用的功能,该功能也常被一些远程操控程序所实用,需要的朋友可以参考下

本文实例讲述了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)

在析构时,调用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; 
}

dll的代码:
.cpp源文件代码:

精彩图集

赞助商链接