鼠标钩子 键盘钩子

时间:2022-11-02 00:32:58

stdafx.h

extern HHOOK g_hMouse;			//全局变量应该在CPP中定义 在头文件中声明

LRESULT CALLBACK MouseProc(int nCode,WPARAM wParam,LPARAM lParam);	//定义鼠标钩子过程

extern HHOOK g_hKeyboard;	
LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam,LPARAM lParam);

stdafx.cpp

HHOOK g_hMouse = NULL;	//钩子型全局变量

LRESULT CALLBACK MouseProc(int nCode,WPARAM wParam,LPARAM lParam)	//定义鼠标钩子过程
{	
	return 0;	//如果钩子函数返回1 表示当前消息已处理,系统不再将这个消息传递给目标窗口过程
			<span style="font-family: Arial, Helvetica, sans-serif;">//窗口也就无法接收鼠标了</span>
}

HHOOK g_hKeyboard = NULL;	//钩子型全局变量

LRESULT CALLBACK KeyboardProc(int nCode,WPARAM wParam,LPARAM lParam)	//定义鼠标钩子过程
{	
	
	if(VK_SPACE == wParam)	//截掉空格键
	{
		return 1;
	}
	else
	{
		return ::CallNextHookEx(::g_hKeyboard,nCode,wParam,lParam);
	}
	
	//return 1;
}
Dlg.cpp
BOOL CHOOKDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// Set the icon for this dialog.  The framework does this automatically
	//  when the application's main window is not a dialog
	SetIcon(m_hIcon, TRUE);			// Set big icon
	SetIcon(m_hIcon, FALSE);		// Set small icon

	// TODO: Add extra initialization here
	
	::g_hMouse=					//全局变量
		::SetWindowsHookExA
		(
		WH_MOUSE,				//鼠标钩子
		::MouseProc,			//
		NULL,					//当前进程 当前线程
		::GetCurrentThreadId()	//当前线程ID
		);

	::g_hKeyboard=					
		::SetWindowsHookExA
		(
		WH_KEYBOARD,				//键盘钩子
		::KeyboardProc,			
		NULL,					
		::GetCurrentThreadId()	
		);
		
	//::AfxMessageBox("hello");
	return TRUE;  // return TRUE  unless you set the focus to a control
}