質問

I would like to know if there is any way to find out if any keys or mouse buttons are pressed without using InputEvent.

For example: My application does not have focus but when it gains it I want to know whether the Ctrl key is pressed or not. This works in most conditions but not if the focus is gained via a click on the title bar (and this is exactly what I'm looking for).

Or: I start dragging a window and I want to know if Ctrl key is pressed or released during this drag.

I have tried listening for Keystrokes and using an AWTEventListener but that doesn't help since there is no information about the pressed keys.

Is there any way to get the pressed keys from Swing? As far as I've searched I don't think there is because the modifiers are gathered in the toolkit directly from the OS generated event (getModifiers() in XWindow for example) but maybe I'm wrong.

There is this way: GlobalKeyListener but it's much to complicated and also OS dependent.

役に立ちましたか?

解決 3

The only actual possibility I found is using https://code.google.com/p/jnativehook/

This adds a native listener using JNI.

他のヒント

The title bar is NOT a Swing component so you can't receive events when you use a Swing listener.

If you want to listen for events then you need to use a JFrame with Swing decorations:

JFrame frame = new JFrame();
frame.setUndecorated(true);
frame.getRootPane().setWindowDecorationStyle(JRootPane.FRAME);
frame.getRootPane().addMouseListener(...);

What about listening for keys and setting some boolean variables. Then when you application gets focus you just check if the booleans are set.

For example

private boolean isCtrlDown;
public void keyPressed(KeyEvent e) {
    if(e.getKeyCode() == KeyEvent.VK_CONTROL) {
        isCtrlDown = true;
    }
}
public void keyReleased(KeyEvent e) {
   if(e.getKeycode() == KeyEvent.VK_CONTROL) {
       isCtrlDown = false;
   }
}


public void focusGained(FocusEvent e) {
     if(isCtrlDown) {
         // Do what you wanted to do
     }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top