Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 235
bigJava Avatar asked Dec 06 '25 14:12

bigJava


2 Answers

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.

like image 91
Evg Evg Avatar answered Dec 08 '25 04:12

Evg Evg


Try out the Robot class to emulate a key press. Use the Key Event class's VK_WINDOWS constant to press the windows key (this can be generalized to also press the up key with VK_UP):

import java.awt.Robot;
import java.awt.event.KeyEvent;
Robot r = new Robot();
r.keyPress(KeyEvent.VK_WINDOWS);
r.keyRelease(KeyEvent.VK_WINDOWS);

Keep in mind the Robot class throws an IllegalArgumentException if the key is invalid. I'm not 100% on what happens if you try to press the Windows key on a non-Windows OS.

like image 25
Peter G Avatar answered Dec 08 '25 02:12

Peter G



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!