有了动态链接库后我们还需要用一个应用程序来设置和记录我们的鼠标和键盘记录.
我们新建一个基于对话框的MFC应用程序工程HookApp.我们首先为我们的自定义消息添加所需消息响应的实现代码.
在对话框类的头文件的protected下面的注释宏中间加入
afx_msg longonHookKey(WPARAM wParam, LPARAM lParam);
afx_msg longonHookMouse(WPARAM wParam, LPARAM lParam);
指明消息处理函数,然后在对话框类的源文件中的
BEGIN_MESSAGE_MAP(CHookAppDlg, CDialog)
和END_MESSAGE_MAP之间加入下面的代码
ON_MESSAGE(HM_KEY,onHookKey)
ON_MESSAGE(HM_MOUSE,onHookMouse)
定义好后在源文件中写其实现函数:
long CHookAppDlg::OnHookKey(WPARAM wParam, LPARAM lParam)
{
// 此时参数wParam为用户按键的虚拟键码,
// lParam参数包含按键的重复次数、扫描码、前一个按键状态等信息
char szKey[80];
::GetKeyNameText(lParam, szKey, 80); //获得按键名
CString strItem;
strItem.Format("用户按键:%s", szKey);
CListBox *pListCtrl=((CListBox *)this->GetDlgItem(IDC_LIST1));
pListCtrl->InsertString(-1,strItem);
CFile MyFile;
char *content;
if(!MyFile.Open(this->MyDocumentDir,
CFile::modeRead | CFile::modeWrite))
{
MyFile.Open(this->MyDocumentDir,
CFile::modeCreate);
return 0;
}
MyFile.SeekToEnd(); //移动记录指针到末尾
pListCtrl->GetText(pListCtrl->GetCount()-1,strItem);
content=strItem.GetBuffer(MAX_PATH);
MyFile.Write(content,strItem.GetLength());
CTime today=CTime::GetCurrentTime();
CString str=today.Format("\t\t%Y年%m月%d日 %H:%M:%S\r\n");
MyFile.Write(str.GetBuffer(str.GetLength()),str.GetLength());
MyFile.Close();
return 0;
}
long CHookAppDlg::OnHookMouse(WPARAM wParam, LPARAM lParam)
{
LPMOUSEHOOKSTRUCT pMouseHook=(MOUSEHOOKSTRUCT FAR *)lParam;
CString strItem,strText;
CListBox *pListCtrl=((CListBox *)this->GetDlgItem(IDC_LIST1));
CPoint point;
::GetCursorPos(&point);
ClientToScreen(&point);
CWnd *pWnd=CWnd::GetForegroundWindow();
if(pWnd)
{
char str[80];
pWnd->GetWindowText(str,80);
strText.Format("窗口:%s",str);
}
CString str;
/*CString tempstr;
// ClientToScreen(&pMouseHook->pt);
int x,y;
x=pMouseHook->pt.x;
y=pMouseHook->pt.y;
tempstr.Format("X=%d,Y=%d",x,y);
strText+=tempstr;*/
if(wParam==WM_RBUTTONDOWN)
{
str.Format(" 右键单击:位置 X=%d,Y=%d",point.x,point.y);
strText+=str;
pListCtrl->InsertString(-1,strText);
this->SaveToFile(strText,pListCtrl);
}
if(wParam==WM_LBUTTONDBLCLK)
{
ScreenToClient(&point);
str.Format(" 左键双击:位置 X=%d,Y=%d",point.x,point.y);
strText+=str;
pListCtrl->InsertString(-1,strText);
this->SaveToFile(