How do I check if the caps lock key is pressed?

前端 未结 3 1786
终归单人心
终归单人心 2020-12-07 01:24

Alright, before this gets flagged as a possible duplicate, I\'ve already tried the following code:

Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK         


        
相关标签:
3条回答
  • 2020-12-07 02:02

    Poking around, I think getLockingKeyState() might be broken.

    You could try KeyboardUtils, but it looks like that means you have to carry JNA overhead.

    0 讨论(0)
  • 2020-12-07 02:04
    public void checkOnOff() {
        Thread th = new Thread() {
            public void run() {
                for (;;) {
                    if (Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK)) {
                        jLabel4.setForeground(Color.red);
                        jLabel4.setText("CAPSLOCK is ON");
                    } else {
                        jLabel4.setText(null);
                    }
                    try {
                        sleep(100);
                    } catch (InterruptedException ex) {
                        Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
                    }                    
                }
            }
        };th.start();
    }
    
    0 讨论(0)
  • 2020-12-07 02:14

    Looks like this was always broken or at least since Java 1.3 (see Bug 4414164).

    Not sure for other platforms, but for Windows I can say this: State change of Caps Lock can be detected, but only if your awt client has the focus. However, there is this workaround which works for me:

    boolean isCapsLockOn() {
        java.awt.Robot robot = new java.awt.Robot();
        robot.keyPress(KeyEvent.VK_CONTROL);
        robot.keyRelease(KeyEvent.VK_CONTROL);
        return Toolkit.getDefaultToolkit().getLockingKeyState(KeyEvent.VK_CAPS_LOCK);  
    }
    

    Contraint: Your awt app must have the focus before calling isCapsLockOn.

    Note: Your robot might press any other key which is not harmful to your app. Might depend on your use case.

    0 讨论(0)
提交回复
热议问题