グローバルなキーボードとマウスのリスナーを作成する 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){}
}