Sending a keyboard event from java to any application (on-screen-keyboard)

11,492

Solution 1

Apparently the only way to do this is to have a JNI layer that will make the conversion from java to native. Java has no easy way to provide such funcionality.

This could be an interesting concept for a small, third party library for someone who wants to learn JNI...

Solution 2

I found jnativehook when I was trying to control a gamebot with actual keyboard and mouse commands (to be more "human-like").

Solution 3

The only solution I could find so far, is to make every key a JComponent (so it can not have focus), and set the following properties on the JFrame:

    setUndecorated(true);
    setFocusableWindowState(false);
    setFocusable(false);
    enableInputMethods(false);

Now when using the robot class I can send events to any focused window by clicking on the keys. The only limitation, is that it only seems to work for windows that belong to the same virtual machine, and it doesn't work at all with any other system window.

Share:
11,492

Related videos on Youtube

Mario Ortegón
Author by

Mario Ortegón

Connected Vehicles Azure Mobility Microsoft Connected Vehicle Platform

Updated on April 19, 2022

Comments

  • Mario Ortegón
    Mario Ortegón about 2 years

    I am working on developing an on-screen keyboard with java. This keyboard has a JComponent for every possible key. When a mouse down is detected on the button, I want to send a specific keyboard code to the application currently on focus. The keyboard itself is within a JFrame with no decorations and set to always-on-top.

    I found that the Robot class can be used to simulate these keyboard events on the native queue. However, in this case, selecting the JComponent would mean that the key-press is received on the JFrame, and I wouldn't be able to receive it in the other application

    How can I keep my on-screen keyboard "Always-without-focus"? Is it maybe possible to use another approach to send the key-press?

  • Simon Forsberg
    Simon Forsberg almost 8 years
    From the description of JNativeHook, it seems like it's for listening for keyboard and mouse events, not for sending events to another application.
  • Alex Jone
    Alex Jone almost 7 years
    Worked perfectly on windows 10, should be number 1 answer, no need for jni