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

3 Answers 3

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!");
2
  • 3
    Also works with VK_SCROLL for Scroll Lock and VK_NUMLOCK for Num Lock. Aug 27, 2016 at 9:41
  • 1
    An important part of this is & 0x0001 because the information is returned in the low-order bit.
    – wrecks
    Jan 22, 2021 at 22:44
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

3
  • 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?
    – user1994036
    Dec 22, 2014 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. Aug 27, 2016 at 9: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 Jan 11, 2017 at 4:23
2

Use GetAsyncKeyState with VK_CAPITAL (0x14)

2
  • 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." Jan 11, 2017 at 4: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, 2022 at 16:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.