21

What is the VK_[key] code for the command key on a mac, if one exists? I am trying to get a Robot (java Robot) to press the command key. I am using the command keyPress(), and I need to know the integer keycode for the command key on a mac.

Abaab
  • 571
  • 1
  • 4
  • 15

3 Answers3

29

KeyEvent.VK_META, with key code 157, is Java's virtual key that maps to the the Mac command key.

FThompson
  • 28,352
  • 13
  • 60
  • 93
  • Is this still working for you? For me this is sadly not working. – lony Jul 26 '18 at 11:32
  • @lony Do you have simple example code I can run to test whether it's working or not? I could write my own test but if you have something that could save me the time that would be much appreciated. – FThompson Jul 26 '18 at 16:29
  • The problem for me was that I needed a delay in between this and the other key selects. Then it worked. – lony Jul 26 '18 at 16:51
2

KeyEvent.VK_META can be used as COMMAND button in Mac OS.

if its not working with you, that is because you need to add a delay

sample code for opening a new tab

Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_META);
robot.delay(200);
robot.keyPress(KeyEvent.VK_T);
robot.keyRelease(KeyEvent.VK_META);
robot.keyRelease(KeyEvent.VK_T);
Mohhamed Nabil
  • 4,104
  • 1
  • 15
  • 11
0

there is also isMetaDown() method, which in my case works if somebody wants to use the shortcuts for copy/paste text and so on.

Sample code:

public void keyPressed(KeyEvent e) {
    if (e.isMetaDown() && (e.getKeyCode() == KeyEvent.VK_V) && readonly.isSelected()){
        e.consume();
    }
}
Dada
  • 6,313
  • 7
  • 24
  • 43