12

How can get whether Caps Lock is on or off? I tried to search it but all I'm finding is how to toggle or turn it on/off which is exactly opposite of what I'm looking for.

I'm trying to do that in both C++ and Delphi.
Please help

SmRndGuy
  • 1,719
  • 5
  • 30
  • 49

3 Answers3

24

I found this link and the code snippet below that might help you

if ((GetKeyState(VK_CAPITAL) & 0x0001)!=0)
  AfxMessageBox("Caps Lock ON!");
else
  AfxMessageBox("Caps Lock OFF!");
Mattias Josefsson
  • 1,147
  • 1
  • 7
  • 22
11

You want the GetKeyState() function:

http://msdn.microsoft.com/en-us/library/ms646301(VS.85).aspx

with the VK_CAPITAL key code. Rest of the virtual key codes are here:

http://technet.microsoft.com/en-us/subscriptions/index/dd375731(v=vs.85).aspx

HerrJoebob
  • 2,264
  • 16
  • 25
  • Doesn't that just get the state of the key? Caps lock is usually used as a toggle. Does this really give you the toggle state for the whole machine? –  Dec 22 '14 at 16:54
  • Yup, it really gives you the toggle state. It's not that intuitive, that this method gives you key presses by the user as well as overall key toggle states. – Jan Feldmann Aug 27 '16 at 09:38
  • "The key status returned from this function changes as a thread reads key messages from its message queue. The status does not reflect the interrupt-level state associated with the hardware. Use the GetAsyncKeyState function to retrieve that information." -- msdn – Orwellophile Jan 11 '17 at 04:23
2

Use GetAsyncKeyState with VK_CAPITAL (0x14)

Bernd Elkemann
  • 23,242
  • 4
  • 37
  • 66
  • 2
    "If the function succeeds, the return value specifies whether the key was pressed since the last call to GetAsyncKeyState, and whether the key is currently up or down. If the most significant bit is set, the key is down, and if the least significant bit is set, the key was pressed after the previous call to GetAsyncKeyState. However, you should not rely on this last behavior; for more information, see the Remarks." – Orwellophile Jan 11 '17 at 04:22
  • 1
    This is incorrect. GetAsyncKeyState() tells you if the physical key is up or down, not if CapsLock is toggled on or off. – egrunin Apr 28 '22 at 16:13