Qt獲取Capslock鍵(大小寫鍵)狀態

2021-09-13 22:41:22 字數 2147 閱讀 7455

1.前言

最近需要qt獲取按鍵ascii碼,可是qkeyevent::key()返回的是鍵碼,不是ascii碼(0-127),需要從鍵碼轉ascii碼。遇到的問題是不知道如何獲取capslock鍵狀態,網友說用lobyte(getkeystate(vk_capital)),但如何跨平台呢,qt不該只用windows吧?

2.解決辦法

用qkeyevent::nativemodifiers()獲取capslock鍵狀態,

keyevent->nativemodifiers() & capslock;

依據原始碼:

const quint32 scancode = (msg.lparam >> 16) & scancodebitmask;

const quint32 vk_key = msg.wparam;

quint32 nmodifiers = 0;

#if defined(q_os_wince)

nmodifiers |= (getkeystate(vk_shift  ) < 0 ? shiftany : 0);

nmodifiers |= (getkeystate(vk_control) < 0 ? controlany : 0);

nmodifiers |= (getkeystate(vk_menu   ) < 0 ? altany : 0);

nmodifiers |= (getkeystate(vk_lwin   ) < 0 ? metaleft : 0);

nmodifiers |= (getkeystate(vk_rwin   ) < 0 ? metaright : 0);

#else

// map native modifiers to some bit representation

nmodifiers |= (getkeystate(vk_lshift  ) & 0x80 ? shiftleft : 0);

nmodifiers |= (getkeystate(vk_rshift  ) & 0x80 ? shiftright : 0);

nmodifiers |= (getkeystate(vk_lcontrol) & 0x80 ? controlleft : 0);

nmodifiers |= (getkeystate(vk_rcontrol) & 0x80 ? controlright : 0);

nmodifiers |= (getkeystate(vk_lmenu   ) & 0x80 ? altleft : 0);

nmodifiers |= (getkeystate(vk_rmenu   ) & 0x80 ? altright : 0);

nmodifiers |= (getkeystate(vk_lwin    ) & 0x80 ? metaleft : 0);

nmodifiers |= (getkeystate(vk_rwin    ) & 0x80 ? metaright : 0);

// add lock keys to the same bits

nmodifiers |= (getkeystate(vk_capital ) & 0x01 ? capslock : 0);

nmodifiers |= (getkeystate(vk_numlock ) & 0x01 ? numlock : 0);

nmodifiers |= (getkeystate(vk_scroll  ) & 0x01 ? scrolllock : 0);

#endif // q_os_wince

if (msg.lparam & extendedkey)

nmodifiers |= msg.lparam & extendedkey;

3. 總結

qkeyevent::key() 返回虛擬鍵碼,比如qt::key_space

qkeyevent::modifiers() 返回shift、ctrl、alt、meta和groupswitch虛擬鍵狀態

qkeyevent::nativescancode() 返回實際鍵碼

qkeyevent::nativemodifiers() 返回capslock、numlock和scrolllock實際鍵狀態

qkeyevent::isautorepeat() 判斷長按

網路資源只作參考,多跟蹤原始碼,以原始碼為主

4.參考文獻

交換caps lock和ctrl鍵

交換capslock和ctrl鍵 直接在登錄檔中修改鍵位對映關係,cmd regedit.exe 登錄檔位置 hkey local machine system currentcontrolset control keyboard layout 如果沒有此鍵,就新建乙個 新建乙個二進位制值的key,...

使用C 開啟Caps lock鍵

在.net winform應用程式中如何開啟capslock 鍵呢?或者在程式啟動的時候,capslock鍵就變亮了呢,今天在國外的乙個論談看到了解決方案,事實上很簡單的.我們只要dllimport attribute 去呼叫系統的函式就可以了.部分 如下 privatevoidform1 load...

交換左Ctrl鍵和Caps lock鍵

windows 10 windows registry editor version 5.00 hkey local machine system currentcontrolset control keyboard layout scancode map hex 00,00,00,00,00,00...