Java 机器人点击侧边按钮

Java Robot click side button

我想用 Robot 来点击鼠标按钮 4,侧边按钮。

InputEvent 只有 3 个标准的左、中(滚动)和右按钮。

InputEvent.BUTTON1_DOWN_MASK = 1024
InputEvent.BUTTON2_DOWN_MASK = 2048
InputEvent.BUTTON3_DOWN_MASK = 4096

所以我尝试使用公式并将数字 8192

发送到 Robot
public static void main(String[] args)
{
    try
    {
        Robot mouseHandler = new Robot();

        mouseHandler.mousePress(8192);
        mouseHandler.mouseRelease(8192);
    } catch (AWTException e)
    {
        e.printStackTrace();
    }
}

但它没有工作(如预期的那样)并抛出异常:

Exception in thread "main" java.lang.IllegalArgumentException: Invalid combination of button flags
    at java.awt.Robot.checkButtonsArgument(Robot.java:320)
    at java.awt.Robot.mousePress(Robot.java:256)
    at controller_client.MainClass.main(MainClass.java:30)

是否可以使用按钮 4 创建鼠标点击?

好的所以在搜索更多之后我发现这个函数 return 从 1 到 20 的任何鼠标按钮掩码 MouseEvent.getMaskForButton(int button)

尝试后 Robot class 确实成功地点击了 button4 和 button5,侧面按钮,如下所示:

try
{
    Robot mouseHandler = new Robot();

    int mouseButtonNum = 4; // 1 - 20
                            // but only buttons from 1 to 5 did work with Robot

    mouseHandler.mousePress(MouseEvent.getMaskForButton(mouseButtonNum));
    mouseHandler.mouseRelease(MouseEvent.getMaskForButton(mouseButtonNum));
} catch (AWTException e)
{
    e.printStackTrace();
}

我使用的鼠标有 3 个按钮,Robot 确实设法单击了 4 个和 5 个按钮。但是好像 Robot 只能点击 1 到 5 的按钮,所以 可能 Hovercraft Full Of Eels 的解释是正确的:

I also have to wonder if your issue is not only OS-specific, but also vendor-specific, since I don't know if handling of extra and perhaps unusual mouse buttons has been fully addressed by most common OS's.

如果他做对了,那么我使用的 OS 是 Windows 10。如果有人有 Linux 并且他知道如何将更多的鼠标按钮指向 Linux并尝试使 Robot 单击鼠标按钮超过 5 所以请注意它是否有效。