How to check for key being held down on startup in Java

陌路散爱 提交于 2019-11-28 12:11:30
public class LockingKeyDemo {
    static Toolkit kit = Toolkit.getDefaultToolkit();

    public static void main(String[] args) {
        System.out.println("caps lock2 = "
                + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
}
}
anjanb
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;

public class LockingKeyDemo {
    static Toolkit kit = Toolkit.getDefaultToolkit();

    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.addWindowListener(new WindowAdapter() {
            public void windowActivated(WindowEvent e) {
                System.out.println("caps lock1 = "
                        + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));

                try {
                    Robot robot = new Robot();
                    robot.keyPress(KeyEvent.VK_CONTROL);
                    robot.keyRelease(KeyEvent.VK_CONTROL);
                } catch (Exception e2) {
                    System.out.println(e2);
                }

                System.out.println("caps lock2 = "
                        + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
            }
        });

        frame.addKeyListener(new KeyAdapter() {
            public void keyReleased(KeyEvent e) {
                System.out.println("caps lock3 = "
                        + kit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK));
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(200, 200);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
Karan

Well there are two types of key press detection: event based, and polling. If you poll the keyboard for KEY_PRESSED on startup (through a loop with a sleep.thread(timeInMs) constantly checking if your key is down), then you can detect if it's already pressed on startup.

The original question seems to be not answered. The proposed method determines the locking key state like CapsLock, ScrollLock, etc. So it would not work for Alt pressed state.

Consider the following code:

com.sun.jna.platform.KeyboardUtils.isPressed(java.awt.event.KeyEvent.VK_ALT);

The only problem is that this class is an internal Sun's JDK class and not likely to be available in any other JVM. Depend on your project it may or may not be acceptable.

Internally it calls into User32.DLL on Windows:

User32.INSTANCE.GetAsyncKeyState(...)

I don't know much about Java (mostly code in C#) but what about having a small loader program written in C or something that then launches your Java app with some parameters (like whether or not a certain key is down)?

So it appears that you can do this, but only for caps lock et al. Hence, I've switched to using caps lock for this purpose. Not perfect, but OK.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!