How can I emulate pressing media keys in Java? Such as play/pause, next/previous, volume control.
C# has VK_MEDIA_PLAY_PAUSE
, VK_MEDIA_NEXT_TRACK
Create your own keylistener and spy for whatever comes and then use this value. Here is simple KeySpy class:
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class KeySpy {
JLabel label=new JLabel("Enter the key");
public KeySpy() {
JFrame frame=new JFrame("KeySpy");
frame.add(label);
frame.addKeyListener(new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
}
@Override
public void keyPressed(KeyEvent e) {
label.setText(e.toString());
System.out.println(e.toString());
}
});
frame.setSize(200, 200);
frame.setVisible(true);
}
public static void main(String[] args) {
new KeySpy();
}
}
and here is result for 2 buttons on my keyboard
[Stop] = java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=178,primaryLevelUnicode=0,scancode=36,extendedKeyCode=0x0] on frame0
[Mute] = java.awt.event.KeyEvent[KEY_PRESSED,keyCode=0,keyText=Unknown keyCode: 0x0,keyChar=Undefined keyChar,keyLocation=KEY_LOCATION_STANDARD,rawCode=173,primaryLevelUnicode=0,scancode=32,extendedKeyCode=0x0] on frame0
As you can see they do not have keyCode but they do have rawCode - so use it.