Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Encoding of key codes (virtual?) send to virtualbox-guest-system

Tags:

java

keycode

How to send a string to a virtualbox-guest-machine?

This is my code:

public void testKeyboard() throws Exception {
    IVirtualBox b = connect();
    List<IMachine> machines = b.getMachines();
    for (IMachine m : machines) {
        MachineState d = b.getMachineStates(Arrays.asList(m)).iterator().next();
        if (d == MachineState.Running) {
            ISession s = manager.getSessionObject();
            m.lockMachine(s, LockType.Shared);
            IConsole console = s.getConsole();
            IKeyboard k = console.getKeyboard();
            k.putScancodes(Arrays.asList(25, 25 | 0x80)); // <- sends the character P
            s.unlockMachine();
        }
    }
}

Microsoft say its 0x50

java.awt.event.KeyEvent also say its 0x50:

/** Constant for the "P" key. */
 public static final int VK_P = 0x50; 

In virtualbox its different. P=25 2=0x50 b=0x30

Why in the world is the code of P = 25 in virtualbox?

like image 438
Grim Avatar asked Oct 18 '25 00:10

Grim


1 Answers

Virtual key codes and keyboard scan codes are two different things.

Keyboards (still) talk to PCs using a really dusty old protocol. Many years ago I implemented a toy version of the protocol in an OS driver and it was quite annoying. Making it worse, keyboards can use 3 different sets of keyboard scancodes which originated with different flavors of old PCs.

Here is a reference for the 3 sets: https://www.vetra.com/scancodes.html

The constants you discovered line up with Set 1. Note that Set 1 has different codes used to press the key and release the key!

The virtual key constants used by the Java KeyEvent class and by that Windows list both seem to be based closely on ASCII characters, since 'P' = 0x50 in ASCII. But it's the job of the operating system keyboard driver to translate from keyboard scancodes to more logical sets of constants. There is no universal constant for a key.

Since VirtualBox is emulating the physical keyboard interface to the guest OS, its IKeyboard API takes raw scancodes.

For the VirtualBox GUI, it must have a function which translates from host OS key constants back to scancodes for the guest OS, which might be easier if you can use that, but IKeyboard appears to be a very low-level interface which bypasses that.

Depending on your use case, perhaps there is a different API you can also use here; or perhaps you can control your VM with guest software like SSH or VNC.

like image 193
Boann Avatar answered Oct 19 '25 14:10

Boann



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!