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.

1
  • 3
    I believe you're after KeyEvent.VK_META, but you will need to test it Commented Mar 14, 2013 at 20:07

3 Answers 3

29

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

Sign up to request clarification or add additional context in comments.

3 Comments

Is this still working for you? For me this is sadly not working.
@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.
The problem for me was that I needed a delay in between this and the other key selects. Then it worked.
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);

Comments

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();
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.