HOWTO: Set the CAPS LOCK, SCROLL LOCK, and NUM LOCK States

Last reviewed: February 11, 1998
Article ID: Q94606

The information in this article applies to:
  • Microsoft Windows Software Development Kit (SDK) for Windows version 3.1

SUMMARY

The current state of the CAPS LOCK, SCROLL LOCK, and NUM LOCK keys can be queried and retrieved by the GetKeyboardState function. Although the SetKeyboardState function works on Windows 3.1x, it does not work correctly on Windows 95 or Windows NT. GetKeyboardState retrieves a byte array describing the state of every key. If the low order bit of a toggle key is set, the key is "on." By changing this bit, the toggle key state can be changed.

MORE INFORMATION

The following sample code demonstrates how to change the state of any key on all platforms. Simply pass the virtual key code (VK_CAPITAL, VK_NUMLOCK or VK_SCROLL) and a flag to set or reset the key state to the PostVirtualKeyEvent:

Sample Code

   #include <windows.h>
   
   #define MAKEWORD(low, high)   ((WORD)(((BYTE)(low)) | \
                                 (((WORD)((BYTE)(high))) << 8)))
   
   void FAR PASCAL Keybd_Event(void);
   
   void FAR PASCAL PostVirtualKey(  BYTE bVirtualKey,
                                    BOOL fKeyUp)
   {
   WORD wARegister, wBRegister;
   
   // Convert the virtual-key code to the scan code
   BRegister = MAKEWORD((BYTE) MapVirtualKey(bVirtualKey, 0), 0);
   ARegister = MAKEWORD(bVirtualKey, (fKeyUp ? 0x80 : 0x00));
   _asm mov bx, wBRegister;   // BH = 0 (No prefix)
   _asm mov ax, wARegister;
   Keybd_Event();
   }
   
   int PASCAL WinMain(  HINSTANCE hInst,
                        HINSTANCE hPrevInst,
                        LPSTR szCmdLine,
                        int nCmdShow)
   {
   // Toggle the caps lock key
   PostVirtualKey(VK_CAPITAL, FALSE);
   PostVirtualKey(VK_CAPITAL, TRUE);
   
   return 0;
   }
Keywords          : UsrInp kb16bitonly
Version           : WIN3.X:3.1
Platform          : WINDOWS
Issue type        : kbhowto


================================================================================


THE INFORMATION PROVIDED IN THE MICROSOFT KNOWLEDGE BASE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. MICROSOFT DISCLAIMS ALL WARRANTIES, EITHER EXPRESS OR IMPLIED, INCLUDING THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL MICROSOFT CORPORATION OR ITS SUPPLIERS BE LIABLE FOR ANY DAMAGES WHATSOEVER INCLUDING DIRECT, INDIRECT, INCIDENTAL, CONSEQUENTIAL, LOSS OF BUSINESS PROFITS OR SPECIAL DAMAGES, EVEN IF MICROSOFT CORPORATION OR ITS SUPPLIERS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES SO THE FOREGOING LIMITATION MAY NOT APPLY.

Last reviewed: February 11, 1998
© 1998 Microsoft Corporation. All rights reserved. Terms of Use.