消除在 Java GUI 中使用 Alt-F4 和 Alt-TAB 的可能性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6127709/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove the possibility of using Alt-F4 and Alt-TAB in Java GUI
提问by n0pe
Possible Duplicate:
Java Full Screen Program (Swing) -Tab/ALT F4
I've got a full screen frame running and I wish to emulate a Kiosk environment. To do this, I need to "catch" all occurrences of Alt-F4and Alt-Tabpressed on the keyboard at all times. Is this even possible? My pseudocode:
我有一个全屏框架正在运行,我希望模拟一个 Kiosk 环境。为此,我需要始终“捕捉”键盘上所有出现的Alt-F4和Alt-Tab按下。这甚至可能吗?我的伪代码:
public void keyPressed(KeyEvent e) {
//get the keystrokes
//stop the closing or switching of the window/application
}
I'm not sure if keyPressed and it's associates (keyReleased and keyTyped) are the right way to go because from what I've read, they only handle single keys/chars.
我不确定 keyPressed 及其关联(keyReleased 和 keyTyped)是否是正确的方法,因为从我读过的内容来看,它们只处理单个键/字符。
回答by Martijn Courteaux
To stop Alt-F4:
要停止 Alt-F4:
yourframe.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
To stop Alt-Tab, you can make something more aggressive.
要停止 Alt-Tab,您可以做一些更激进的事情。
public class AltTabStopper implements Runnable
{
private boolean working = true;
private JFrame frame;
public AltTabStopper(JFrame frame)
{
this.frame = frame;
}
public void stop()
{
working = false;
}
public static AltTabStopper create(JFrame frame)
{
AltTabStopper stopper = new AltTabStopper(frame);
new Thread(stopper, "Alt-Tab Stopper").start();
return stopper;
}
public void run()
{
try
{
Robot robot = new Robot();
while (working)
{
robot.keyRelease(KeyEvent.VK_ALT);
robot.keyRelease(KeyEvent.VK_TAB);
frame.requestFocus();
try { Thread.sleep(10); } catch(Exception) {}
}
} catch (Exception e) { e.printStackTrace(); System.exit(-1); }
}
}