//首先定义
HWND g_hWnd; //定义一个窗口的句柄
HHOOK g_hMouse; //鼠标的钩子过程
HHOOK g_hKeyBoard; //键盘的钩子过程
//鼠标钩子过程的回调函数
HRESULT CALLBACK MouseProc(int nCode, WPARAM wParam, LPARAM lParam)
{
return 1;
}
//键盘钩子过程的回调函数
HRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam)
{
/*
if(VK_SPACE==wParam) //VK_SPACE为设备虚拟码,表示空格
//我们可以选择go to definition找到其他虚拟码,如果我们
//同时屏蔽掉回车键,这时按键盘上的Alt+F4键可以退出。
//如果你连Alt+F4都想屏蔽,添加以下判断语句
//if(VK_F4==wParam && (lParam>>29 & 1))
//lParam右移29位,正好它的第二十九位在第一位上,
//lParam得第二十九位表示了Alt键被按下
return 1;
*/
///使程序在F2键按下后退出/
if(VK_F2==wParam)
{
//::SendMessage(g_hWnd,WM_CLOSE,0,0); //发送关闭消息
UnhookWindowsHookEx(g_hKeyBoard);
UnhookWindowsHookEx(g_hMouse);//移除一个已经安装的hook
//当我们自己发送消息关闭程序时,一定要记得关闭Hook
return 1;
}
else
return CallNextHookEx(g_hKeyBoard,nCode,wParam,lParam);
//返回下一个钩子过程(一次按键相当于一个钩子过程)
}
BOOL CTTDDDlg::OnInitDialog()
{
CDialog::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_hWnd = m_hWnd; //获得当前窗口的句柄,供回调函数用
// 安装一个鼠标hook,GetCurrentThreadId()返回调用线程的线程标识
g_hMouse = SetWindowsHookEx(WH_MOUSE,MouseProc,NULL,GetCurrentThreadId());
// 安装一个键盘hook
g_hKeyBoard = SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,NULL,GetCurrentThreadId());
return TRUE; // return TRUE unless you set the focus to a control
}