Jna Keyboard Hook in Windows

JNA Keyboard Hook in Windows

It appears you need to call GetMessage or PeekMessage, which is odd - it is not mentioned in the documentation for Hooks or LowLevelKeyboardProc. I don't know enough about this part of the API to guess at the reason.

I just used the example classes:

import com.sun.jna.examples.win32.*;

public class Callback {
public static User32.HHOOK hHook;
public static User32.LowLevelKeyboardProc lpfn;
public static volatile boolean quit = false;

public static void main(String[] args) throws Exception {
W32API.HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
lpfn = new User32.LowLevelKeyboardProc() {
public W32API.LRESULT callback(int nCode, W32API.WPARAM wParam,
User32.KBDLLHOOKSTRUCT lParam) {
System.out.println("here");
quit = true;
return User32.INSTANCE.CallNextHookEx(hHook, nCode, wParam, lParam
.getPointer());
}
};
hHook = User32.INSTANCE.SetWindowsHookEx(User32.WH_KEYBOARD_LL, lpfn, hMod,
0);
if (hHook == null)
return;
User32.MSG msg = new User32.MSG();
while (!quit) {
User32.INSTANCE.PeekMessage(msg, null, 0, 0, 0);
Thread.sleep(100);
}
if (User32.INSTANCE.UnhookWindowsHookEx(hHook))
System.out.println("Unhooked");
}
}

C++/Java - Keyboard Hook

I'm not exactly sure what you want for your C++ code, but here's how you would make it work with Java:

Look into JNI, it'll explain how to execute native code through Java

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html

Essentially, you use a tool to create glue headers that you include in your C++ application. The Java code will automatically call the native library when you call a native function.

Also keep in mind that there's a speed penalty for going from native to java layer.

How to use SetWindowsHookEx function with java?

Take a look at jnativehook. It's a library for using system-wide keyboard / mouse hooks from Java.



Related Topics



Leave a reply



Submit