#include <imm.h> #pragma comment(lib, "imm32")2、定义变量:
//键盘钩子句柄 HHOOK g_hKeyboardHook = NULL; //是否拦截Backspace bool g_bInterceptBackspace = true;
3、定义键盘钩子回调函数:
LRESULT CALLBACK KeyboardHookProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode > -1) { BOOL bRet = FALSE; LPKBDLLHOOKSTRUCT lpKeyboard = (LPKBDLLHOOKSTRUCT)lParam; HWND hCurWnd = ::GetFocus(); HIMC hImc = ImmGetContext(hCurWnd); LONG nSize = ImmGetCompositionString(hImc, GCS_COMPSTR, NULL, 0);
ImmReleaseContext(hCurWnd, hImc); if (hImc) { if (nSize > 0) { //如果按键组合窗口字符串长度大于0,则表明显示了按键组合窗口,交给系统默认处理 g_bInterceptBackspace = false; bRet = TRUE; } else if (nSize == 0) { if (!g_bInterceptBackspace) { //如果按键组合框窗口字符串等于0,且上次显示了按键组合框窗口,则表明是删除最后一个字符后,交给系统默认处理 g_bInterceptBackspace = true; bRet = TRUE; } } }
if (VK_BACK == wParam) { if (!bRet) { if (lParam & 0x80000000) { ::SendMessage(::GetFocus(), WM_KEYUP, VK_BACK, 0); } else { ::SendMessage(hCurWnd, WM_KEYDOWN, VK_BACK, 0); ::SendMessage(hCurWnd, WM_CHAR, VK_BACK, 0); } return 1; } } } return CallNextHookEx(g_hKeyboardHook, nCode, wParam, lParam); }
4、安装钩子
g_hKeyboardHook = ::SetWindowsHookEx(WH_KEYBOARD, (HOOKPROC)KeyboardHookProc, 0, GetCurrentThreadId());
5、卸载钩子
::UnhookWindowsHookEx(g_hKeyboardHook);