Search code examples
javakeyboardkeyboard-shortcuts

How to click Windows key in Java


Can I click "Windows" key in Java? I need to emulate pressing Win + ARROW_UP keys. May be this button has Key Unicode and it could be called by .getKeyFromUnicode() method? Will be appreciated for any help. Thank you.


Solution

  • 1) You can simply try this:

    private void pressKey() {
    
        try {
            Robot r = new Robot();
            r.keyPress(KeyEvent.VK_WINDOWS)
            r.keyPress(KeyEvent.VK_UP); //Windows button is still pressed at this moment
            r.keyRelease(KeyEvent.VK_UP);
            r.keyRelease(KeyEvent.VK_WINDOWS);          
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    2) Another variant for solving your task - is sikuli.docs

    If you want to simulate pressing and holding one button, while then typing another, use type(TheKeyDoingTheAction, KeyModifier.TheKeyYoureHoldingDown It's written like this:

     type(Key.UP, KeyModifier.WIN)
    

    Please check docs and samples here: http://doc.sikuli.org/keys.html

    3) Finally, you could use the following code:

    Runtime.getRuntime().exec("rundll32 user32.dll,LockWorkStation");
    

    Note: This will work for Win OS only.