Aller au contenu

Simulating key presses in your program with keybd_event function

Oct 11, 2009 | 42Gears Team

Out of need or curiosity you might want to know how to send key presses from your native application. The core of the solution involves calling keybd_event() function which has the following prototype.

VOID keybd_event(BYTE bVk, BYTE bScan, DWORD dwFlags, DWORD dwExtraInfo);

bVk is the virtual-key code of the character. bScan is the hardware scan code. dwFlags is an important field. If KEYEVENTF_KEYUP is specified in dwFlags field, the key is being released. If not specified, the key is being pressed.

Here is a function which simulates pressing of alphanumeric characters. See winuser.h for all available virtual key codes.

void SendStringKeys(char* pszChars)
{
while (*pszChars != NULL)
{
if ( (*pszChars >= ‘A’) && (*pszChars <= ‘Z’) )
keybd_event(VK_SHIFT, 0, KEYEVENTF_SILENT, 0);

keybd_event(toupper(*pszChars), 0, KEYEVENTF_SILENT, 0);
keybd_event(toupper(*pszChars), 0, KEYEVENTF_KEYUP|KEYEVENTF_SILENT, 0);

if ( (*pszChars >= ‘A’) && (*pszChars <= ‘Z’) )
keybd_event(VK_SHIFT, 0, KEYEVENTF_KEYUP|KEYEVENTF_SILENT, 0);

pszChars++;
}
}

And here is an example of how to call SendStringKeys function.

int _tmain(int argc, _TCHAR* argv[])
{
SendStringKeys(“Hello World.”);
return 0;
}

Subscribe for our free newsletter

Thank you! you are successfully subscribed.
newsletter

Exclusive News and Updates on Enterprise Mobility!

* I consent to receive newsletters via email from 42Gears and its Affiliates.
Please agree
* I have reviewed and agreed to 42Gears Privacy Policy and Terms of Use prior to subscribing and understand that I may change my preference or unsubscribe at any time.
Please agree
Please verify captcha
Please enter a valid official email