SetWindowsHookEx WH_KEYBOARD_LL在右移时没有响应

时间:2013-09-19 17:02:04

标签: c++ windows winapi visual-c++ keyboard-hook

我尝试在c ++中使用Windows API,SetWindowsHookEx WH_KEYBOARD_LL似乎没有从右边的 Shift 键获取事件( Shift 键入qwerty键盘的右侧,在 Enter 键下方。它适用于左 Shift 键。我如何解决这个问题?

#include "stdafx.h"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <string>
#include <windows.h>
#include <string> 
#include <shlobj.h>
#include <Shlwapi.h>
#include <stdio.h>
#include <aclapi.h>
#include <tchar.h>
#include <iostream>
#include <fstream>
#include <future>
#include <stdlib.h>
#include <random>
#include <ctime>
#include <time.h>       
#include <Lmcons.h>



HHOOK   kbdhook;    /* Keyboard hook handle */
bool    running;    /* Used in main loop */


__declspec(dllexport) LRESULT CALLBACK handlekeys(int code, WPARAM wp, LPARAM lp)
{
        static bool capslock = false;
        static bool shift = false;
        char tmp[0xFF] = {0};
        std::string str;
        DWORD msg = 1;
        KBDLLHOOKSTRUCT st_hook = *((KBDLLHOOKSTRUCT*)lp);



        msg += (st_hook.scanCode << 16);
        msg += ((st_hook.flags & LLKHF_EXTENDED) << 24);
        GetKeyNameText(msg, tmp, 0xFF);
        str = std::string(tmp);


    if (code == HC_ACTION && (wp == WM_SYSKEYDOWN || wp == WM_KEYDOWN )) {
        MessageBox(NULL,str.c_str(),NULL,MB_OK);
}
return CallNextHookEx(kbdhook, code, wp, lp);
}

LRESULT CALLBACK windowprocedure(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp)
{
    switch (msg) {
        case WM_CLOSE: case WM_DESTROY:
            running = false;
            break;
        default:
            /* Call default message handler */
            return DefWindowProc(hwnd, msg, wp, lp);
    }

    return 0;
}

int WINAPI WinMain(HINSTANCE thisinstance, HINSTANCE previnstance,
        LPSTR cmdline, int ncmdshow)
{


    HWND        hwnd;
    HWND        fgwindow = GetForegroundWindow(); 
    MSG     msg;
    WNDCLASSEX  windowclass;
    HINSTANCE   modulehandle;

    modulehandle = GetModuleHandle(NULL);
    kbdhook = SetWindowsHookEx(WH_KEYBOARD_LL, (HOOKPROC)handlekeys, modulehandle, NULL);
    running = true;






    while (running) {

        if (!GetMessage(&msg, NULL, 0, 0))
            running = false; 
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return 0;
}

右移在警报中显示一个blanco字符串。然而,左移在警报中显示“SHIFT”字符串。任何人都有线索???

PS:

如果我删除了“msg + =((st_hook.flags&amp; LLKHF_EXTENDED)&lt;&lt; 24);” - &GT; “RIGHT SHIFT”现在显示,但是在按下“Windows键”时显示未定义

2 个答案:

答案 0 :(得分:1)

左移与右移显示在vkCode的{​​{1}}字段中。您正在使用扫描码的密钥名称;右移键被命名为'Shift',就像它在键盘上所说的那样。

显然,右移最终会设置扩展标志,这会导致GetKeyNameText查找错误的表。删除扩展标志的最后一个键名为“右移”。

KBDLLHOOKSTRUCT

答案 1 :(得分:1)

此解决方案不依赖于特定代码

if (st_hook.vkCode != VK_RSHIFT)
  msg += ((st_hook.flags & LLKHF_EXTENDED) << 24);