当按引号键时,java.awt.Robot.keyPress引发IllegalArgumentException [英] java.awt.Robot.keyPress throws IllegalArgumentException when when pressing quotation mark key

查看:122
本文介绍了当按引号键时,java.awt.Robot.keyPress引发IllegalArgumentException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您尝试使用Robot.keyPress键入"(双引号)时,它将引发java.lang.IllegalArgumentException:无效的键代码.

When you try to use Robot.keyPress to type a " (double quotation mark) it throws a java.lang.IllegalArgumentException: Invalid key code.

我该如何解决或解决这个问题?

How can I fix or get around this?

如果有帮助,我目前在Windows上.

If it helps, I am currently on Windows.

测试代码:

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Test {
    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        try {
            robot.keyPress(KeyEvent.VK_QUOTEDBL);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

例外:

java.lang.IllegalArgumentException: Invalid key code
    at sun.awt.windows.WRobotPeer.keyPress(Native Method)
    at java.awt.Robot.keyPress(Robot.java:358)

推荐答案

我认为您遇到了错误,因为键盘上没有"键. "几乎可以肯定会在键盘的键之一上,但是很有可能会被移动.而不是试图按" ",而是应该按" Shift和该键的基本"字符,即,如果您自己键入该键,则会得到一个键.

I think you're getting an error because there isn't a " key on your keyboard. " will almost certainly be on one of the keys of your keyboard but it will quite probably be shifted. Instead of trying to 'press' ", you should be 'pressing' Shift and the 'base' character for that key, i.e. the one you get if you type that key on its own.

我发现,在命令提示符下运行以下类会给我一个"字符:

I found that running the following class in a command-prompt left me with a " character:

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Test {
    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        try {
            robot.keyPress(KeyEvent.VK_SHIFT);
            robot.keyPress(KeyEvent.VK_2);
            robot.keyRelease(KeyEvent.VK_SHIFT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

在英国键盘(我正在使用)上,"字符被移了2,这就是为什么我使用KeyEvent.VK_2的原因.它可能在其他键盘上的其他位置-如果我没记错的话,它在美国键盘上是单引号引起来的.在这种情况下,您将使用VK_QUOTE而不是VK_2.

On a UK keyboard (which I'm using), the " character is shifted 2, which is why I'm using KeyEvent.VK_2. It may be in other places on other keyboards - if I remember correctly, it's shifted single-quote on a US keyboard. In that case, you would use VK_QUOTE instead of VK_2.

我还发现释放VK_SHIFT按键对于避免Windows认为仍然按住Shift键的各种奇怪操作是必要的.

I also found that releasing the VK_SHIFT keypress was necessary to avoid all sorts of weirdness with Windows thinking the Shift key was still held down.

这篇关于当按引号键时,java.awt.Robot.keyPress引发IllegalArgumentException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆