如何在 Java 中检查启动时是否按下了按键
我正在尝试编写一个在程序首次启动时弹出的分辨率选择对话框。 为了防止用户感到无聊,我想实现一个相当标准的功能,您可以使用复选框关闭该对话框,但在启动时按住 alt 键可以将其恢复。
不幸的是,没有明显的方法来询问 java 是否当前正在按下给定的键。 您只能通过 KeyListener 注册以获取新按键的通知,但如果按键在应用程序启动之前启动,则这无济于事。
I'm trying to write a resolution selection dialog that pops up when a program first starts up. To prevent boring the user, I want to implement the fairly standard feature that you can turn off that dialog with a checkbox, but get it back by holding down the alt key at startup.
Unfortunately, there is no obvious way to ask java whether a given key is currently being pressed. You can only register to be informed of new key presses via a KeyListener, but that doesn't help if the keypress starts before the app launches.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
按键检测有两种类型:基于事件和轮询。 如果您在启动时轮询键盘是否有
KEY_PRESSED
(通过使用sleep.thread(timeInMs)
不断检查按键是否按下的循环),那么您可以检测到它是否已按下已经按下启动按钮。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 asleep.thread(timeInMs)
constantly checking if your key is down), then you can detect if it's already pressed on startup.原来的问题似乎没有得到解答。 所提出的方法确定锁定键状态,如 CapsLock、ScrollLock 等。因此它不适用于 Alt 按下状态。
考虑以下代码:
com.sun.jna.platform.KeyboardUtils.isPressed(java.awt.event.KeyEvent.VK_ALT);
唯一的问题是该类是 Sun 的内部 JDK 类,而不是可能在任何其他 JVM 中都可用。 取决于您的项目,它可能会也可能不会被接受。
它在内部调用 Windows 上的 User32.DLL:
User32.INSTANCE.GetAsyncKeyState(...)
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(...)
我不太了解 Java(主要是 C# 代码),但是用 C 编写一个小型加载程序或使用一些参数(例如是否按下某个键)启动 Java 应用程序怎么样?
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.