Java Robot click side button

荒凉一梦 提交于 2020-05-15 09:13:12

问题


I want to use Robot to click mouse button 4, side button.

The InputEvent only have the 3 standard left, middle (scroll) and right buttons.

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

So I tried to flow the formula and send to the Robot the number 8192

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

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

but it didn't work (as expected) and throws an exception:

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)

Is it possible to create a mouse click with button 4?


回答1:


Ok so after searching more I found this function that return any mouse button mask from 1 to 20 MouseEvent.getMaskForButton(int button).

After trying it the Robot class did manage to click the button4 and button5, side buttons, like so:

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();
}

I used a mouse with 3 buttons and Robot did manage to click 4 and 5 buttons. But it seems like that Robot only can click buttons from 1 to 5, so probably Hovercraft Full Of Eels's explanation is correct:

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.

If he does right then the OS that I use is Windows 10. If someone have Linux and he knows how to address more mouse buttons to Linux and tried to make Robot click mouse button above 5 so please note me if it works or not.



来源:https://stackoverflow.com/questions/55436569/java-robot-click-side-button

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