// 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的返回句柄。