3

How to make a simple C program which will produce keyboard key hits.

if ( condition ) {
    KeyPress('A');
}

I am working on Ubuntu 8.10 Linux OS

Madni
  • 143
  • 1
  • 4
  • 16

6 Answers6

15

Here's a simple example using libxdo (from xdotool). (Caveat: I am the xdotool author)

 /* File: testkey.c
 *
 * Compile with:
 * gcc -lxdo testkey.c
 *
 * Requires libxdo (from xdotool project)
 */

#include <xdo.h>

int main() {
  xdo_t *xdo = xdo_new(NULL);
  xdo_keysequence(xdo, CURRENTWINDOW, "A", 0);
  return  0;
}
  • 3
    It seems `xdo_keysequence` has been renamed to `xdo_send_keysequence_window`; in Ubuntu 14.04 at least. By the way, should I call `xdo_free` afterwards? libxdo is very nice by the way, I'd suggest a one-page tutorial for it - it took me an hour to get here; trawling through xdotool code, I had no idea I could get away without a `context`. – user2023370 Nov 01 '14 at 18:17
2

There is XTestFakeKeyEvent() function from Xlib.

You can USE Expect for c or C++ Programs

joe
  • 34,529
  • 29
  • 100
  • 137
2

Take a look at xsendkey. The sources are included and are short, so you extract the necessary parts from it into your program.

Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54
1

Although this is not C, you can produce key hits in Java very easily:

import java.awt.Robot;
import java.awt.AWTException;
import java.awt.event.KeyEvent;


public class key
{
    public static void main(String args[])
    {
        try {
            Robot r = new Robot();
            r.delay(2000);
            r.keyPress(KeyEvent.VK_W);
        } catch (AWTException e) {
            e.printStackTrace();
        }
    }
};
Adrian Panasiuk
  • 7,249
  • 5
  • 33
  • 54
0

Have a look at Swinput.

Swinput can fake a mouse and a keyboard by using the Linux Input System. The swinput modules read from a device and fakes hardware event (mouse motion, key presses etc) as commands written on the devices.

Lars Haugseth
  • 14,721
  • 2
  • 45
  • 49
  • Thanks ! It seems Swinput works with kernel space. I am looking for some user space application – Madni Jul 10 '09 at 12:06
0

Get Fake Key Events by Xdotool

//Compile As:  gcc button.c -lX11 

#include < X11/Xlib.h >
#include < X11/Xutil.h >
#include < stdio.h >
#include < X11/extensions/XTest.h >

void press_button()
{   
    Display *d;
    d = XOpenDisplay(NULL);
        if(d == NULL)
        {
            //fprintf(stderr, "Errore nell'apertura del Display !!!\n");
            //exit(0);
        }
    system("xdotool key Shift+a");
    XFlush(d);
    XCloseDisplay(d);
}

int main() {
    press_button();
    return 0;
}
Trevor Hickey
  • 36,288
  • 32
  • 162
  • 271
Madni
  • 143
  • 1
  • 4
  • 16