I want to get my program to unhide main window when user presses some shortcut. Is there a way to get the global key events, not only the ones which happened when focus was inside application frame?
3 Answers
This might do what you want. Note that this code is checking for a Ctr-F keystroke. I use this code to open up a find dialog from anything in the application. I'm pretty sure that the app has to have focus though. Something to try at least...
AWTEventListener listener = new AWTEventListener() {
@Override
public void eventDispatched(AWTEvent event) {
try {
KeyEvent evt = (KeyEvent)event;
if(evt.getID() == KeyEvent.KEY_PRESSED && evt.getModifiers() == KeyEvent.CTRL_MASK && evt.getKeyCode() == KeyEvent.VK_F) {
}
}
catch(Exception e) {
e.printStackTrace();
}
}
};
Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
EDIT: I think I understand what you want. Basically when the app does NOT have focus. If so then you'll probably have to hook into the OS events with a native API (JNI) but that forces you to a specific OS...

- 494
- 2
- 4
-
Sad. I hoped there will be some platform-independent way :( – Rogach Jan 05 '11 at 21:20
-
Make sure to check the link that altanis provided below. That has a little discussion about (possibly) why it is not in Java. Something about maybe OSX does not have that. I have not done enough OSX programming to know if that is true or false though... – Merky Jan 05 '11 at 21:29
-
This is what I call "slipshod" answer. This code is **useless** as it is. You must implement it with the appropriate import(s) and use of this kbd listener! In short, a fully workable code! Moreover, I don't think that it workds w/o using a Jframe or other kind of frame. This is definitely a "downvote" case, however, I never do it. I prefer commenting on it. – Apostolos Feb 04 '22 at 11:06
This might be useful. I'm not sure if there is one library that will work for Windows/Linux/Mac. For Windows you will need some external library that uses native code to create a keyboard hook. I have no idea how to do it on the other OSes.

- 1
- 1

- 2,667
- 15
- 33
A solution to do this by using a JFrame is to set his opacity to 0.0 and to add the Keylistener to it. But the user will see an icon in his shortcut bar...

- 26
- 1
-
This method will not allow the user to interact with windows behind the JFrame. And the JFrame would still have to be in focus. – Coding Mason Feb 24 '21 at 05:33