delphiwinapidelphi-2009

Simulating keyboard input in Delphi using WinAPI


I need to programmatically enter one character into a cell of a Delphi grid (in other application).

In order to do this manually, following steps are required:

  1. Press the F3 button.
  2. Press the right-arrow key 3 times.
  3. Press the space button.
  4. Type letter 'E' on the keyboard.
  5. Press the right-arrow key.

     // Press F3 button         
     keybd_event(VK_F3, 0, 0, 0);         
     // Press right arrow key 3 times
     keybd_event(VK_RIGHT, 0, 0, 0);
     keybd_event(VK_RIGHT, 0, 0, 0);
     keybd_event(VK_RIGHT, 0, 0, 0);
    
     // Press the space button
     keybd_event(VK_SPACE, 0, 0, 0);
    
     // Type letter E
     keybd_event(Ord('E'), 0, 0, 0);
    
     // Move to the right
     keybd_event(VK_RIGHT, 0, 0, 0);
    

But it doesn't work. When I run this code, nothing seems to happen.

How should I modify this code so that it actually simulates user input?


Solution

  • Each key press is a key down and then a key up. So you need two calls to keybd_event per key press. For example, to press F3:

    keybd_event(VK_F3, 0, KEYEVENTF_KEYDOWN, 0);
    keybd_event(VK_F3, 0, KEYEVENTF_KEYUP, 0);
    

    Note that KEYEVENTF_KEYDOWN isn't actually defined by the Windows header files, or the Delphi translation. Define it to be 0. It makes the code clearer written out explicitly though.

    Naturally you would not litter your code with paired calls to keybd_event. But instead you would wrap up the paired calls into a helper function.

    It's possible that in some situations you would need to specify the second parameter, the scan code. But it's often not necessary.