65.9K
CodeProject is changing. Read more.
Home

Simulate a keystroke in windows

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.79/5 (16 votes)

Feb 14, 2011

CPOL
viewsIcon

43366

This tip shows how to simulate a key stroke in windows environment

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 );
}
Reference MSDN (Thanx to Victor Nijegorodov)