# CodeGuru Technical FAQs > CodeGuru Individual FAQs >  Windows SDK User Interface: How can I emulate keyboard events in an application?

## golanshahar

*Q:* How can I emulate keyboard events in an application?

*A:*
 There are two API functions that you can use:

'keybd_event()''SendInput()'.

Before emulating a keystroke we must make sure that:

 The window we want to send the keystroke must be in focus and active. That we have the virtual key code for the key we want to generate.

The keys 'A-Z' and the keys '0-9' have a virtual key code that is the same as their ASCII code. For example, in order to generate the letter A we need to use the 'A' (or 65) as the virtual key code.

Look here for a complete list of virtual key codes.
 Which of the two API functions should I use?

The 'keybd_event()' function has been superseded by 'SendInput()' on Window NT/2000/XP. Thus, on these operating systems you should use 'SendInput()' (unless you need to provide backward compatibility with Windows 98 etc.). This FAQ is based on 'SendInput()'.
 Can I see some example on how to use 'SendInput()'?



```
void GenerateKey ( int vk , BOOL bExtended)
{
  KEYBDINPUT  kb={0};
  INPUT    Input={0};
  // generate down 
  if ( bExtended )
    kb.dwFlags  = KEYEVENTF_EXTENDEDKEY;
  kb.wVk  = vk;  
  Input.type  = INPUT_KEYBOARD;

  Input.ki  = kb;
  ::SendInput(1,&Input,sizeof(Input));

  // generate up 
  ::ZeroMemory(&kb,sizeof(KEYBDINPUT));
  ::ZeroMemory(&Input,sizeof(INPUT));
  kb.dwFlags  =  KEYEVENTF_KEYUP;
  if ( bExtended )
    kb.dwFlags  |= KEYEVENTF_EXTENDEDKEY;

  kb.wVk    =  vk;
  Input.type  =  INPUT_KEYBOARD;
  Input.ki  =  kb;
  ::SendInput(1,&Input,sizeof(Input));
}
```

 How to use the function? 

Suppose we want to generate 'a' key and then 'A' key:



```
GenerateKey ('A', FALSE);
GenerateKey (VK_CAPITAL, TRUE);
GenerateKey ('A', FALSE);
```


The output will be 'aA' (in case the 'CapsLock' initial state is on, the output will be 'Aa').

*NOTE:*

 In case 'CapsLock' is pressed the letter that will be generated will be uppercase ('A') The generated letter also depends on the input locale of thread that will receive the key.

Thanks to *cilu* for helping writing this FAQ.

----------

