Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
690 views
in Technique[技术] by (71.8m points)

Simulate keypress in a Linux C console application

Is there any way to simulate a keypress in Linux using C?

In my specific situation, I'm on Ubuntu 9.04 and need a simple app that invokes a press on the "pause" button when launched. That would get an iframe in Firefox to refresh using Javascript.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I assume you mean the "X11 application" - it is not entirely clear from your description what you are planning to do. The below code snippet will send the "pause" keycode to the application that currently has the keyboard input focus under X11 using XTest extension - from what I've read this is the most compatible way to "fake" the keyboard events. See if you might apply this to your scenario (no error check on whether the XOpenDisplay succeeded, to make it simpler).

#include <X11/Xlib.h>
#include <X11/keysym.h>
#include <X11/extensions/XTest.h>
...
Display *display;
unsigned int keycode;
display = XOpenDisplay(NULL);
...
keycode = XKeysymToKeycode(display, XK_Pause);
XTestFakeKeyEvent(display, keycode, True, 0);
XTestFakeKeyEvent(display, keycode, False, 0);
XFlush(display);

You will need to link with the -lX11 -lXtst.

Obviously the firefox would need to have focus at that time.

However, I would be curious to know what is the bigger task that you are trying to accomplish - I suspect there should be a more elegant solution than spoofing the keypress events.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...