通过JNI 技术实现 键盘监听

 

 

  1. #include "jni.h"
  2. #include "windows.h"
  3. #include "SystemKey.h"
  4. #include <iostream>
  5. using namespace std;
  6. JNIEnv* _env;
  7. jclass _obj;
  8. jmethodID _id;
  9. HHOOK g_hook = NULL;
  10. LRESULT CALLBACK KeyboardProc(int nCode, WPARAM wParam, LPARAM lParam){
  11.     if(nCode>=0 && g_hook != NULL){
  12.         (*_env).CallStaticVoidMethod(_obj,_id,wParam);
  13.     }
  14.     return CallNextHookEx(g_hook,nCode,wParam,lParam);
  15. }
  16. JNIEXPORT void JNICALL Java_SystemKey_Init(JNIEnv * env, jobject obj){
  17.     _obj = (*env).GetObjectClass(obj);
  18.     _id = (*env).GetStaticMethodID(_obj,"KeyAction","(I)V");
  19.     _env = env;
  20.     g_hook = SetWindowsHookEx(WH_KEYBOARD,KeyboardProc,GetModuleHandle("KeyListenerDLL"),0);
  21. }
  22. JNIEXPORT void JNICALL Java_SystemKey_UnHook(JNIEnv * env, jobject obj){
  23.     UnhookWindowsHookEx(g_hook);
  24. }

 

 

 

 

  1. public class SystemKey{
  2.     private static SystemKeyListener listener = null;
  3.     private boolean out = true;
  4.     public SystemKey(){
  5.         Init();
  6.     }
  7.     static{
  8.         System.loadLibrary("KeyListenerDLL");
  9.     }
  10.     public void addSystemKeyListener(SystemKeyListener listener){
  11.         this.listener = listener;
  12.     }
  13.     public static void KeyAction(int key){
  14.         if(listener!=null)
  15.             listener.keyPressed(key);
  16.     }
  17.     public void removeSystemKeyListener(SystemKeyListener listener){
  18.         if(this.listener.equals(listener)){
  19.             this.listener = null;
  20.         }
  21.     }
  22.     public native void Init();
  23.     public native void UnHook();
  24.     protected void finalize(){
  25.         UnHook();
  26.     }
  27. }
 
  1. public interface SystemKeyListener{
  2.     public void keyPressed(int key);
  3. }

 

 

 

  1. import java.awt.*;
  2. import javax.swing.*;
  3. public class Test extends JFrame implements SystemKeyListener{
  4.     public Test(){
  5.         this.setSize(50,50);
  6.         this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
  7.         this.setResizable(false);
  8.         SystemKey k = new SystemKey();
  9.         k.addSystemKeyListener(this);
  10.         k.removeSystemKeyListener(this);
  11.         this.show(true);
  12.     }
  13.     public void keyPressed(int key){
  14.         System.out.println(key);
  15.     }
  16.     public static void main(String [] args){
  17.             new Test();
  18.     }
  19. }

 

 

 

 

 

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值