Notice: This website is an unofficial Microsoft Knowledge Base (hereinafter KB) archive and is intended to provide a reliable access to deleted content from Microsoft KB. All KB articles are owned by Microsoft Corporation. Read full disclaimer for more details.

HOWTO: Toggle the NUM LOCK, CAPS LOCK, and SCROLL LOCK Keys


Summary

The documentation for SetKeyboardState() correctly says that you cannot use this API to toggle the NUM LOCK, CAPS LOCK, and SCROLL LOCK keys.


You can use keybd_event() to toggle the NUM LOCK, CAPS LOCK, and SCROLL LOCK keys under Windows NT. The same technique works for toggling CAPS LOCK and SCROLL LOCK under Windows 95, but it will not work for NUM LOCK.

↑ Back to the top


More Information

The following sample program turns the NUM LOCK light on if it is off. The SetNumLock function defined here simulates pressing the NUM LOCK key, using keybd_event() with a virtual key of VK_NUMLOCK. It takes a boolean value that indicates whether the light should be turned off (FALSE) or on (TRUE).


The same technique can be used for the CAPS LOCK key (VK_CAPITAL) and the SCROLL LOCK key (VK_SCROLL).

Sample Code

   /* Compile options needed:
*/

#include <windows.h>

void SetNumLock( BOOL bState )
{
BYTE keyState[256];

GetKeyboardState((LPBYTE)&keyState);
if( (bState && !(keyState[VK_NUMLOCK] & 1)) ||
(!bState && (keyState[VK_NUMLOCK] & 1)) )
{
// Simulate a key press
keybd_event( VK_NUMLOCK,
0x45,
KEYEVENTF_EXTENDEDKEY | 0,
0 );

// Simulate a key release
keybd_event( VK_NUMLOCK,
0x45,
KEYEVENTF_EXTENDEDKEY | KEYEVENTF_KEYUP,
0);
}
}

void main()
{
SetNumLock( TRUE );
}

↑ Back to the top


Keywords: kb, kbkeyin, kbinput, kbhowto

↑ Back to the top

Article Info
Article ID : 127190
Revision : 7
Created on : 8/20/2020
Published on : 8/20/2020
Exists online : False
Views : 158