- #include "jni.h"
- #include "windows.h"
- #include "SystemKey.h"
- #include <iostream>
- using namespace std;
- JNIEnv* _env;
- jclass _obj;
- jmethodID _id;
- HHOOK g_hook = NULL;
- LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam){
- if(nCode>=0 && g_hook != NULL){
- (*_env).CallStaticVoidMethod(_obj,_id,wParam);
- }
- return CallNextHookEx(g_hook,nCode,wParam,lParam);
- }
- JNIEXPORT void JNICALL Java_SystemKey_Init(JNIEnv * env, jobject obj){
- _obj = (*env).GetObjectClass(obj);
- _id = (*env).GetStaticMethodID(_obj,"KeyAction","(I)V");
- _env = env;
- g_hook = SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,GetModuleHandle("KeyListenerDLL"),0);
- }
- JNIEXPORT void JNICALL Java_SystemKey_UnHook(JNIEnv * env, jobject obj){
- UnhookWindowsHookEx(g_hook);
- }
- public class SystemKey{
- private static SystemKeyListener listener = null;
- private boolean out = true;
- public SystemKey(){
- Init();
- }
- static{
- System.loadLibrary("KeyListenerDLL");
- }
- public void addSystemKeyListener(SystemKeyListener listener){
- this.listener = listener;
- }
- public static void KeyAction(int key){
- if(listener!=null)
- listener.keyPressed(key);
- }
- public void removeSystemKeyListener(SystemKeyListener listener){
- if(this.listener.equals(listener)){
- this.listener = null;
- }
- }
- public native void Init();
- public native void UnHook();
- protected void finalize(){
- UnHook();
- }
- }
- public interface SystemKeyListener{
- public void keyPressed(int key);
- }
- import java.awt.*;
- import javax.swing.*;
- public class Test extends JFrame implements SystemKeyListener{
- public Test(){
- this.setSize(50,50);
- this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
- this.setResizable(false);
- SystemKey k = new SystemKey();
- k.addSystemKeyListener(this);
- k.removeSystemKeyListener(this);
- this.show(true);
- }
- public void keyPressed(int key){
- System.out.println(key);
- }
- public static void main(String [] args){
- new Test();
- }
- }