我只能找出两种截取java中的键的方法。
如果您想为独立的 java 应用程序执行此操作,则必须使用 JNI 在本机执行此操作。您可以谷歌查找 C/C++ 库以拦截密钥。然后您可以在 java 中加载 dll 来帮助您满足您的要求。
如果您正在编写基于 SWING 的 GUI,那么您可以将 keypress lisenter 添加到您的组件中。您可能必须递归地将其添加到所有组件中才能在 UI 的任何级别拦截密钥。这是一个示例代码:
使用以下方法将关键侦听器添加到组件及其子组件:
private void addKeyAndContainerListenerRecursively(Component c)
{
//Add KeyListener to the Component passed as an argument
c.addKeyListener(this);
//Check if the Component is a Container
if(c instanceof Container) {
//Component c is a Container. The following cast is safe.
Container cont = (Container)c;
//Add ContainerListener to the Container.
cont.addContainerListener(this);
//Get the Container's array of children Components.
Component[] children = cont.getComponents();
//For every child repeat the above operation.
for(int i = 0; i < children.length; i++){
addKeyAndContainerListenerRecursively(children[i]);
}
}
}
获取按键事件的方法:
public void keyPressed(KeyEvent e)
{
int code = e.getKeyCode();
if(code == KeyEvent.VK_ESCAPE){
//Key pressed is the Escape key. Hide this Dialog.
setVisible(false);
}
else if(code == KeyEvent.VK_ENTER){
//Key pressed is the Enter key. Redefine performEnterAction() in subclasses
to respond to pressing the Enter key.
performEnterAction(e);
}
//Insert code to process other keys here
}
希望能帮助到你!