package key;
import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.HHOOK;
import com.sun.jna.platform.win32.WinUser.KBDLLHOOKSTRUCT;
import com.sun.jna.platform.win32.WinUser.LowLevelKeyboardProc;
import com.sun.jna.platform.win32.WinUser.MSG;
/**
* Sample implementation of a low-level keyboard hook on W32.
*/
public class teste2 {
private static volatile boolean quit;
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
public static void main(String[] args) {
final User32 lib = User32.INSTANCE;
HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
keyboardHook = new LowLevelKeyboardProc() {
public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {
if (nCode >= 0) {
switch (wParam.intValue()) {
case User32.WM_KEYUP:
case User32.WM_KEYDOWN:
case User32.WM_SYSKEYUP:
case User32.WM_SYSKEYDOWN:
System.err.println("in callback, key=" + info.vkCode);
if (info.vkCode == 81) {
quit = true;
}
}
}
return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());
}
};
hhk = lib.SetWindowsHookEx(User32.WH_KEYBOARD_LL, keyboardHook, hMod, 0);
System.out.println("Keyboard hook installed, type anywhere, 'q' to quit");
//noinspection ConstantConditions
new Thread() {
public void run() {
while (!quit) {
try {
Thread.sleep(10);
} catch (Exception e) {
e.printStackTrace();
}
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
// This bit never returns from GetMessage
MSG msg = new MSG();
while ((lib.GetMessage(msg, null, 0, 0)) != 0) {
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
lib.UnhookWindowsHookEx(hhk);
}
}
Este código funciona, só que esta capturando uma tecla quando é pressionada e quando é liberada
Alguém saberia me dizer como capturar somente quando a tecla é pressionada ?