// ChildView.cpp : implementation of the CChildView class
//
#include "stdafx.h"
#include "MouseHook.h"
#include "ChildView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
HHOOK hHook;
CPoint point;
CChildView *pView;
char gstr[256]="123456";
LRESULT CALLBACK MouseProc(int nCode,WPARAM wParam,LPARAM lParam)
{
//鼠标移动消息
if(wParam==WM_MOUSEMOVE||wParam==WM_NCMOUSEMOVE)
{
point = ((MOUSEHOOKSTRUCT *)lParam)->pt;
pView ->Invalidate();
}
if(wParam==WM_LBUTTONDOWN)
{
sprintf(gstr,"fuck");
}
return CallNextHookEx(hHook,nCode,wParam,lParam);
}
/
// CChildView
CChildView::CChildView()
{
pView = this;
hHook = SetWindowsHookEx(WH_MOUSE,MouseProc,0,GetCurrentThreadId());
}
CChildView::~CChildView()
{
if(hHook)
UnhookWindowsHookEx(hHook);
}
BEGIN_MESSAGE_MAP(CChildView,CWnd )
//{{AFX_MSG_MAP(CChildView)
ON_WM_PAINT()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/
// CChildView message handlers
BOOL CChildView::PreCreateWindow(CREATESTRUCT& cs)
{
if (!CWnd::PreCreateWindow(cs))
return FALSE;
cs.dwExStyle |= WS_EX_CLIENTEDGE;
cs.style &= ~WS_BORDER;
cs.lpszClass = AfxRegisterWndClass(CS_HREDRAW|CS_VREDRAW|CS_DBLCLKS,
::LoadCursor(NULL, IDC_ARROW), HBRUSH(COLOR_WINDOW+1), NULL);
return TRUE;
}
void CChildView::OnPaint()
{
CPaintDC dc(this); // device context for painting
char str[256];
sprintf(str,"x=%d,y=%d",point.x,point.y);
dc.TextOut(0,0,str);
dc.TextOut(50,50,gstr);
// TODO: Add your message handler code here
// Do not call CWnd::OnPaint() for painting messages
}
1。先写自己的消息处理函数,如上面的MouseProc来处理自己感兴趣的消息(WM_MOUSEMOVE,WM_NCMOUSEMOVE,WM_LBUTTONDOWN(我感兴趣的是鼠标移动与单击左键))
注:最好在自己的函数的最后调用 CallNextHookEx() 以让消息继续向下传递。(当然如果是想屏蔽的就用了:))
2。通过SetWindowsHookEx()把自己的函数放到消息处理函数链表的队首
HHOOK SetWindowsHookEx(
int idHook, // type of hook to install Hook的类型,看入门篇
HOOKPROC lpfn, // address of hook procedure 处理函数指针,这里即上面的MouseProc
HINSTANCE hMod, // handle to application instance 应用程序实例句柄,线程钩子为0
DWORD dwThreadId // identity of thread to install hook for 所要监视的纯种ID
);
以上就完成了钩子函数的编写与投放,其已经开始工作
3。不用以后 记得释放啊。。
用UnhookWindowsHookEx(HHOOK hHook); 其参数为投放钩子函数时 SetWindowsHookEx的返回句柄。