import com.sun.jna.examples.win32.Kernel32;
import com.sun.jna.examples.win32.User32;
import com.sun.jna.examples.win32.User32.HHOOK;
import com.sun.jna.examples.win32.User32.KBDLLHOOKSTRUCT;
import com.sun.jna.examples.win32.User32.LowLevelKeyboardProc;
import com.sun.jna.examples.win32.User32.MSG;
import com.sun.jna.examples.win32.W32API.HMODULE;
import com.sun.jna.examples.win32.W32API.LRESULT;
import com.sun.jna.examples.win32.W32API.WPARAM;
public class Dlltest extends Thread{
private static volatile boolean quit = false;
private static HHOOK hhk;
private static LowLevelKeyboardProc keyboardHook;
int WH_KEYBOARD_LL = 13;
public Dlltest() {
new Thread(this).start();
}
@Override
public void run() {
// TODO 자동 생성된 메소드 스텁
super.run();
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) {
test.area.setText("in callback, key=" + info.vkCode);
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(WH_KEYBOARD_LL, keyboardHook, hMod,0);
System.out.println("Keyboard hook installed, type anywhere, 'q' to quit");
new Thread() {
public void run() {
while (!quit) {
try {
Thread.sleep(10);
} catch (Exception e) {
}
}
System.err.println("unhook and exit");
lib.UnhookWindowsHookEx(hhk);
System.exit(0);
}
}.start();
// This bit never returns from GetMessage
int result;
MSG msg = new MSG();
while ((result = lib.GetMessage(msg, null, 0, 0)) != 0) {
if (result == -1) {
System.err.println("error in get message");
break;
} else {
System.err.println("got message");
lib.TranslateMessage(msg);
lib.DispatchMessage(msg);
}
}
System.out.println(result);
lib.UnhookWindowsHookEx(hhk);
}
}
//============================================
JNA 를 사용한 java 에서 키보드 전역 후킹