【发布时间】:2014-09-17 07:36:10
【问题描述】:
我遇到了一个奇怪的问题,我真的不知道如何解决。我正在用 C++ 编写代码,它应该在按下键时触发事件。我可以使用GetAsyncKeystate 很好地检测按键并释放,但我无法可靠地将检测到的按键状态转换为 unicode。 (请注意,我使用的是 Qt,但这并不重要)
我的新闻/发布检测:
// This function is called in a loop
void KeyboardApi::Check()
{
bool stat = false;
for (int i = 7; i < 255; i++) { // 0 undefined, 3 VK_CANCEL can be ignored, 1 2 4 5 6 mouse keys, these are ignored
stat = ((GetAsyncKeyState(i) & 0x8000) != 0);
if (this->first_time) { // To prevent reporting keypresses upon initialization
this->first_time = false;
this->keystate[i] = stat;
continue;
}
if (stat != this->keystate[i]) {
this->keystate[i] = stat;
if (i == VK_SHIFT)
this->shift = stat;
else if (i == VK_CONTROL)
this->ctrl = stat;
else if (i == VK_MENU)
this->alt = stat;
HKL locale = GetKeyboardLayout(GetCurrentThreadId());
// ---!! If this portion is commented, the code does not work correctly.
// if this portion is *not* commented, the code works fine...
/*
std::wcout << "args for keycode_to_unicode:" << std::endl
<< " keycode: " << i << std::endl
<< " locale: " << locale << std::endl
<< " shift: " << this->shift << std::endl;
*/
// ---!!
QString key_string = keycode_to_unicode(i, locale, this->shift);
if (stat)
std::wcout << "Key pressed: " << i << " unicode: " << key_string.toStdWString() << std::endl;
}
}
}
还有 keycode_to_unicode 函数:
QString keycode_to_unicode(unsigned int key, HKL keyboardLayoutHandle, bool shiftPressed)
{
int scanCodeEx = MapVirtualKeyExW(key, MAPVK_VK_TO_VSC_EX, keyboardLayoutHandle);
if (scanCodeEx > 0) {
unsigned char lpKeyState[256];
if (shiftPressed) {
lpKeyState[VK_SHIFT] = 0x80;
lpKeyState[VK_LSHIFT] = 0x80;
}
wchar_t buffer[5];
int rc = ToUnicodeEx(key, scanCodeEx, lpKeyState, buffer, 5, 0, keyboardLayoutHandle);
if (rc > 0) {
return QString::fromWCharArray(buffer);
} else {
// It's a dead key; let's flush out whats stored in the keyboard state.
rc = ToUnicodeEx(key, scanCodeEx, lpKeyState, buffer, 5, 0, keyboardLayoutHandle);
return QString();
}
}
return QString();
}
所以奇怪的是,当我在那里有调试输出时,KeyboardApi::Check() 工作正常,但是当我没有它时,转换为 unicode 会出错。例如,当我第一次按下'A'键时,输出'a'。第二次,'β','β'等
编辑:
你可能会问自己为什么我不使用 Qt 的内置 onKeyPress... 这是因为我的代码被注入到其他进程中,所以我不能使用这种方法。
【问题讨论】: