为什么一些KeyEvent键码抛出“IllegalArgumentException:无效的密钥代码”? [英] Why are some KeyEvent keycodes throwing "IllegalArgumentException: Invalid key code"?
问题描述
我正在尝试使用 Robot
自动执行某些进程,并且在<$ c $中似乎是某些密钥代码(只有在正常输入时才需要保留shift的符号) c> KeyEvent 抛出 IllegalArgumentException
。这是在 main
中运行的所有代码:
I'm trying to automate some processes using Robot
and it seems certain keycodes (only symbols that require you to hold shift when typing it normally) in KeyEvent
are throwing an IllegalArgumentException
. This is all the code that's running in main
:
Robot r = new Robot();
r.keyPress(KeyEvent.VK_EXCLAMATION_MARK);
但是,使用以下解决方法可以正常工作:
However, it works fine using the following workaround:
Robot r = new Robot();
r.keyPress(KeyEvent.VK_SHIFT);
r.keyPress(KeyEvent.VK_1);
为什么抛出异常的想法?谢谢!
Any ideas why the exception is thrown? Thanks!
Java版本:1.6.0_23
Java version: 1.6.0_23
推荐答案
因为喜欢 Robot.keyPress
的文档说, keycode $时会抛出
IllegalArgumentException
c $ c>不代表有效密钥, VK_EXCLAMATION_MARK
不是有效密钥。
Because like the documentation for Robot.keyPress
says, an IllegalArgumentException
is thrown when the keycode
doesn't represent a valid key, and VK_EXCLAMATION_MARK
is not a valid key.
密钥代码是用于表示两件事:键盘上的键和键入字符事件。键入一个字符通常需要多个按键(按顺序,或同时,或两者)。但 Robot.keyPress
模拟按键的行为(因此名称),而不是键入字符的行为。
Keycodes are used to represent two things: keys on the keyboard, and "a character was typed" events. Typing a character often requires more than one keypress (in sequence, or simultaneously, or both). But Robot.keyPress
simulates the act of pressing a key (hence the name), not the act of typing a character.
有关详细信息,请参阅KeyEvent的文档: http:/ /download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html
For more information, see the documentation for KeyEvent: http://download.oracle.com/javase/6/docs/api/java/awt/event/KeyEvent.html
这篇关于为什么一些KeyEvent键码抛出“IllegalArgumentException:无效的密钥代码”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!