键盘挂钩CTRL键被卡住

键盘挂钩CTRL键被卡住

本文介绍了C ++键盘挂钩CTRL键被卡住的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Windows 10机器上的 + 和 + 重写为添加一些其他功能.

I'm looking to rewrite + and + on my Windows 10 machine to add some additional functionality.

我能够正确地复制和粘贴,并在按下这些键后成功创建了一个键盘挂钩来执行我的代码,但是当我的程序在按下后出现问题在运行时,会像被按住一样连续运行.即使我完全终止了程序,在我完全注销计算机之前,仍会像被按住一样继续工作.我该怎么做才能纠正这个问题?

I'm able to copy and paste correctly and have successfully created a keyboard hook to execute my code after these keys are pressed but I'm having an issue after I press while my program is running, continuously acts as if it's held down. Even after I terminate the program entirely, continues to act as if it's being held down until I logout of the computer entirely. What can I do to correct this?

谢谢!

经过一番混乱之后,我可以得出结论,任何键都卡住了. Shift和Caps锁定也会卡住.

after doing a bit of messing around, I can conclude any key gets stuck. Shift and caps lock get stuck as well.

#include <Windows.h>
#include <stdio.h>
#include <queue>

using namespace std;

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
    if (wParam == WM_KEYDOWN) {
        if (p->vkCode == 0x43 && GetKeyState(VK_CONTROL) & 0x8000) { // ctrl-c is pressed
            WM_COPY;
        }
        else if (p->vkCode == 0x56 && GetKeyState(VK_CONTROL) & 0x8000) { // ctrl-v is pressed
            OpenClipboard(NULL);
            char* buffer;
            buffer = (char*)GetClipboardData(CF_TEXT);
            CloseClipboard();
            cout << buffer;
        }
        return CallNextHookEx(NULL, nCode, wParam, lParam);
    }
}

int main()
{
    HHOOK keyBoard = SetWindowsHookEx(WH_KEYBOARD_LL, KeyboardProc, NULL, NULL);
    MSG msg;

    while (!GetMessage(&msg, NULL, NULL, NULL)) {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    UnhookWindowsHookEx(keyBoard);
}

推荐答案

请勿将return CallNextHookEx(NULL, nCode, wParam, lParam)放在if (wParam == WM_KEYDOWN)中.

修改:

LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    PKBDLLHOOKSTRUCT p = (PKBDLLHOOKSTRUCT)lParam;
    if (wParam == WM_KEYDOWN) {
        if (p->vkCode == 0x43 && GetKeyState(VK_CONTROL) & 0x8000) { // ctrl-c is pressed
            WM_COPY;
        }
        else if (p->vkCode == 0x56 && GetKeyState(VK_CONTROL) & 0x8000) { // ctrl-v is pressed
            OpenClipboard(NULL);
            char* buffer;
            buffer = (char*)GetClipboardData(CF_TEXT);
            CloseClipboard();
            cout << buffer;
        }

    }
    return CallNextHookEx(NULL, nCode, wParam, lParam);
}

这篇关于C ++键盘挂钩CTRL键被卡住的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 21:09