我有一个执行 JNativeHook.jar 的线程,它创建了一个全局键盘和鼠标侦听器。根据用户输入,线程可以这样做。
当用户(假设)按下 VK_SPACE 时,我想停止所有线程执行。我想生成另一个也监视键盘的线程,当它再次获得 VK_SPACE 时,它会告诉主线程恢复。
这种操作在 Java 中是否可行,它看起来如何?
这是一些可以使用的代码和JNativeHook .jar
代码:
import org.jnativehook.GlobalScreen;
import org.jnativehook.NativeHookException;
import org.jnativehook.keyboard.NativeKeyEvent;
import org.jnativehook.keyboard.NativeKeyListener;
public class GlobalKeyListenerExample implements NativeKeyListener
{
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_ESCAPE)
{
GlobalScreen.unregisterNativeHook();
}
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE)
{
WatchForMe w = new WatchForMe(this);
w.start();
this.wait();
}
}
public void nativeKeyReleased(NativeKeyEvent e){}
public void nativeKeyTyped(NativeKeyEvent e){}
public static void main(String[] args)
{
try
{
GlobalScreen.registerNativeHook();
}
catch (NativeHookException ex)
{
System.err.println("There was a problem registering the native hook.");
System.exit(1);
}
//Construct the example object and initialze native hook.
GlobalScreen.getInstance().addNativeKeyListener(new GlobalKeyListenerExample());
}
}
public class WatchForMe implements NativeKeyListener
{
boolean alive = true;
Thread me = null;
public WatchForMe(Thread me)
{
if(me == null) return;
this.me = me;
GlobalScreen.getInstance().addNativeKeyListener(this);
}
public void nativeKeyPressed(NativeKeyEvent e)
{
System.out.println("Key Pressed: " + NativeKeyEvent.getKeyText(e.getKeyCode()));
if (e.getKeyCode() == NativeKeyEvent.VK_SPACE)
{
me.notify();
alive = false;
}
}
public void run()
{
while(alive){}
}
public void nativeKeyReleased(NativeKeyEvent e){}
public void nativeKeyTyped(NativeKeyEvent e){}
}