Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 520
Dmitrii Pisarenko Avatar asked Oct 18 '12 09:10

Dmitrii Pisarenko


People also ask

How do you simulate keystrokes?

To simulate native-language keystrokes, you can also use the [Xnn] or [Dnn] constants in the string passed to the Keys method. nn specifies the virtual-key code of the key to be “pressed”. For instance, [X221]u[X221]e will “type” the u and e characters with the circumflex accent.

Can Python simulate keyboard input?

Simulate Keyboard Using the keyboard Library in Python This library can listen to and send keyboard events, use hotkeys, support internationalization, and provide mouse support with the help of the mouse library, which we can download using pip install mouse or pip3 install mouse .


1 Answers

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.

like image 132
David Heffernan Avatar answered Sep 23 '22 03:09

David Heffernan