您的位置:首页 > 其它

通过JNI 技术实现 键盘监听

2008-08-25 10:34 232 查看
 

 

#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();

    }

}

 

 

 

 

 

 

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息