java实现鼠标和键盘动作后台监听

有的时候需要我们对鼠标和键盘的动作(鼠标的移动,键盘的点击)进行监听,比如按键记录,鼠标坐标记录等。

我们使用JNA来实现以上的操作

 tips:JNA类库使用一个很小的本地类库sub 动态的调用本地代码。程序员只需要使用一个特定的java接口描述一下将要调用的本地代码的方法的结构和一些基本属性。这样就省了为了适配多个平台而大量的配置和编译代码。因为调用的都是JNA提供的公用jar 包中的接口。

首先我们实现监听鼠标的代码如下

[java] view plain copy
  1. package getInfo;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Date;  
  9.   
  10. import com.sun.jna.Structure;  
  11. import com.sun.jna.examples.win32.Kernel32;  
  12. import com.sun.jna.examples.win32.User32;  
  13. import com.sun.jna.examples.win32.User32.HHOOK;  
  14. import com.sun.jna.examples.win32.User32.MSG;  
  15. import com.sun.jna.examples.win32.W32API.HMODULE;  
  16. import com.sun.jna.examples.win32.W32API.LRESULT;  
  17. import com.sun.jna.examples.win32.W32API.WPARAM;  
  18. import com.sun.jna.examples.win32.User32.HOOKPROC;  
  19.   
  20. public class MouseHook implements Runnable{  
  21.       
  22.     public static final int WM_MOUSEMOVE = 512;  
  23.     private static HHOOK hhk;  
  24.     private static LowLevelMouseProc mouseHook;  
  25.     final static User32 lib = User32.INSTANCE;  
  26.     private boolean [] on_off=null;  
  27.   
  28.     public MouseHook(boolean [] on_off){  
  29.         this.on_off = on_off;  
  30.     }  
  31.   
  32.     public interface LowLevelMouseProc extends HOOKPROC {  
  33.         LRESULT callback(int nCode, WPARAM wParam, MOUSEHOOKSTRUCT lParam);  
  34.     }  
  35.   
  36.     public static class MOUSEHOOKSTRUCT extends Structure {  
  37.         public static class ByReference extends MOUSEHOOKSTRUCT implements  
  38.         Structure.ByReference {  
  39.         };  
  40.         public User32.POINT pt;  
  41.         public int wHitTestCode;  
  42.         public User32.ULONG_PTR dwExtraInfo;  
  43.     }  
  44.   
  45.     public void run() {  
  46.         HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);  
  47.         mouseHook = new LowLevelMouseProc() {  
  48.             public LRESULT callback(int nCode, WPARAM wParam,  
  49.                     MOUSEHOOKSTRUCT info) {  
  50.                 SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");  
  51.                 SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  52.                 String fileName=df1.format(new Date());  
  53.                 String time=df2.format(new Date());  
  54.                 BufferedWriter bw1=null;  
  55.                 BufferedWriter bw2=null;  
  56.                 try {  
  57.                     bw1=new BufferedWriter(new FileWriter(new File(".//log//"+fileName+"_Mouse.txt"),true));  
  58.                     bw2=new BufferedWriter(new FileWriter(new File(".//log//"+fileName+"_Common.txt"),true));  
  59.                 } catch (IOException e) {  
  60.                     e.printStackTrace();  
  61.                 }  
  62.                 if (on_off[0] == false) {  
  63.                     System.exit(0);  
  64.                 }  
  65.                 if (nCode >= 0) {  
  66.                     switch (wParam.intValue()) {  
  67.                     case MouseHook.WM_MOUSEMOVE:  
  68.                         try {  
  69.                             bw1.write(time+"  ####  "+"x=" + info.pt.x  
  70.                                     + " y=" + info.pt.y+"\r\n");  
  71.                             bw2.write(time+"  ####  "+"x=" + info.pt.x  
  72.                                     + " y=" + info.pt.y+"\r\n");  
  73.                             bw1.flush();  
  74.                             bw2.flush();  
  75.                         } catch (IOException e) {  
  76.                             e.printStackTrace();  
  77.                         }  
  78.                     }  
  79.                 }  
  80.                 return lib  
  81.                 .CallNextHookEx(hhk, nCode, wParam, info.getPointer());  
  82.             }  
  83.         };  
  84.         hhk = lib.SetWindowsHookEx(User32.WH_MOUSE_LL, mouseHook, hMod, 0);  
  85.         int result;  
  86.         MSG msg = new MSG();  
  87.         while ((result = lib.GetMessage(msg, null00)) != 0) {  
  88.             if (result == -1) {  
  89.                 System.err.println("error in get message");  
  90.                 break;  
  91.             } else {  
  92.                 System.err.println("got message");  
  93.                 lib.TranslateMessage(msg);  
  94.                 lib.DispatchMessage(msg);  
  95.             }  
  96.         }  
  97.         lib.UnhookWindowsHookEx(hhk);  
  98.     }  
  99. }  
能够在鼠标移动的时候输出鼠标的坐标位置

接下来是监听键盘的代码

[java] view plain copy
  1. package getInfo;  
  2.   
  3. import java.io.BufferedWriter;  
  4. import java.io.File;  
  5. import java.io.FileWriter;  
  6. import java.io.IOException;  
  7. import java.text.SimpleDateFormat;  
  8. import java.util.Date;  
  9.   
  10. import com.sun.jna.examples.win32.Kernel32;  
  11. import com.sun.jna.examples.win32.User32;  
  12. import com.sun.jna.examples.win32.User32.HHOOK;  
  13. import com.sun.jna.examples.win32.User32.KBDLLHOOKSTRUCT;  
  14. import com.sun.jna.examples.win32.User32.LowLevelKeyboardProc;  
  15. import com.sun.jna.examples.win32.User32.MSG;  
  16. import com.sun.jna.examples.win32.W32API.HMODULE;  
  17. import com.sun.jna.examples.win32.W32API.LRESULT;  
  18. import com.sun.jna.examples.win32.W32API.WPARAM;  
  19.   
  20.   
  21. public class KeyboardHook implements Runnable{  
  22.   
  23.     private static HHOOK hhk;  
  24.     private static LowLevelKeyboardProc keyboardHook;  
  25.     final static User32 lib = User32.INSTANCE;  
  26.     private boolean [] on_off=null;  
  27.   
  28.     public KeyboardHook(boolean [] on_off){  
  29.         this.on_off = on_off;  
  30.     }  
  31.   
  32.     public void run() {  
  33.   
  34.         HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);  
  35.         keyboardHook = new LowLevelKeyboardProc() {  
  36.             public LRESULT callback(int nCode, WPARAM wParam, KBDLLHOOKSTRUCT info) {  
  37.                 SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");  
  38.                 SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  39.                 String fileName=df1.format(new Date());  
  40.                 String time=df2.format(new Date());  
  41.                 BufferedWriter bw1=null;  
  42.                 BufferedWriter bw2=null;  
  43.                 try {  
  44.                     bw1=new BufferedWriter(new FileWriter(new File(".//log//"+fileName+"_Keyboard.txt"),true));  
  45.                     bw2=new BufferedWriter(new FileWriter(new File(".//log//"+fileName+"_Common.txt"),true));  
  46.                   
  47.                 } catch (IOException e) {  
  48.                     e.printStackTrace();  
  49.                 }  
  50.                 if (on_off[0] == false) {  
  51.                     System.exit(0);  
  52.                 }  
  53.                 try {  
  54.                     bw1.write(time+"  ####  "+info.vkCode+"\r\n");  
  55.                     bw2.write(time+"  ####  "+info.vkCode+"\r\n");  
  56.                     bw1.flush();  
  57.                     bw2.flush();  
  58.                 } catch (IOException e) {  
  59.                     e.printStackTrace();  
  60.                 }  
  61.                 return lib.CallNextHookEx(hhk, nCode, wParam, info.getPointer());  
  62.             }  
  63.         };  
  64.         hhk = lib.SetWindowsHookEx(User32.WH_KEYBOARD_LL, keyboardHook, hMod, 0);  
  65.         int result;  
  66.         MSG msg = new MSG();  
  67.         while ((result = lib.GetMessage(msg, null00)) != 0) {  
  68.             if (result == -1) {  
  69.                 System.err.println("error in get message");  
  70.                 break;  
  71.             } else {  
  72.                 System.err.println("got message");  
  73.                 lib.TranslateMessage(msg);  
  74.                 lib.DispatchMessage(msg);  
  75.             }  
  76.         }  
  77.         lib.UnhookWindowsHookEx(hhk);  
  78.     }  
  79.   
  80. }  

最后是获取进程信息的代码

[java] view plain copy
  1. package getInfo;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileWriter;  
  7. import java.io.IOException;  
  8. import java.io.InputStreamReader;  
  9. import java.text.SimpleDateFormat;  
  10. import java.util.Date;  
  11.   
  12. public class ProcessInfo implements Runnable{  
  13.   
  14.     private boolean [] on_off=null;  
  15.   
  16.     public ProcessInfo(boolean [] on_off){  
  17.         this.on_off = on_off;  
  18.     }  
  19.   
  20.     public void run() {  
  21.         BufferedReader input = null;  
  22.         Process process = null;  
  23.         BufferedWriter bw=null;  
  24.         SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");  
  25.         SimpleDateFormat df2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
  26.         String fileName=null;  
  27.         String time=null;  
  28.         try {  
  29.             while(on_off[0]){  
  30.                 fileName=df1.format(new Date());  
  31.                 time=df2.format(new Date());  
  32.                 bw=new BufferedWriter(new FileWriter(new File(".//log//"+fileName+"_ProcessInfo.txt"),true));  
  33.                 Thread.sleep(60000);  
  34.                 process = Runtime.getRuntime().exec("cmd.exe   /c   tasklist");  
  35.                 input =new BufferedReader(  
  36.                         new InputStreamReader(process.getInputStream()));  
  37.                 String line = " ";  
  38.                 int i=0;  
  39.                 input.readLine();  
  40.                 input.readLine();  
  41.                 input.readLine();  
  42.                 while ((line = input.readLine()) != null) {  
  43.                     bw.write(time+"  ####  "+line+"\r\n");  
  44.                     bw.flush();  
  45.                     i++;  
  46.                 }  
  47.             }  
  48.         } catch (Exception e) {  
  49.             e.printStackTrace();  
  50.         } finally{  
  51.             try {  
  52.                 bw.close();  
  53.                 input.close();  
  54.             } catch (IOException e) {  
  55.                 e.printStackTrace();  
  56.             }  
  57.         }  
  58.     }  
  59.   
  60. }  

开启上述线程的类

[java] view plain copy
  1. package getInfo;  
  2.   
  3. import java.awt.AWTException;    
  4. import java.awt.Image;    
  5. import java.awt.MenuItem;    
  6. import java.awt.PopupMenu;    
  7. import java.awt.SystemTray;    
  8. import java.awt.Toolkit;    
  9. import java.awt.TrayIcon;    
  10. import java.awt.event.ActionEvent;    
  11. import java.awt.event.ActionListener;    
  12.   
  13. public class Monitor  {    
  14.   
  15.     public Monitor()  {    
  16.         boolean [] on_off={true};  
  17.         new Thread(new ProcessInfo(on_off)).start();  
  18.         new Thread(new KeyboardHook(on_off)).start();  
  19.         new Thread(new MouseHook(on_off)).start();  
  20.         final TrayIcon trayIcon;    
  21.   
  22.         if (SystemTray.isSupported()) {    
  23.   
  24.             SystemTray tray = SystemTray.getSystemTray();    
  25.             Image image = Toolkit.getDefaultToolkit().getImage(".//lib//monitor.png");    
  26.   
  27.             ActionListener exitListener = new ActionListener() {    
  28.                 public void actionPerformed(ActionEvent e) {    
  29.                     System.out.println("Exiting...");    
  30.                     System.exit(0);    
  31.                 }  
  32.             };    
  33.   
  34.             PopupMenu popup = new PopupMenu();    
  35.             MenuItem defaultItem = new MenuItem("Exit");    
  36.             defaultItem.addActionListener(exitListener);    
  37.             popup.add(defaultItem);    
  38.   
  39.             trayIcon = new TrayIcon(image, "monitor", popup);    
  40.   
  41.             ActionListener actionListener = new ActionListener() {    
  42.                 public void actionPerformed(ActionEvent e) {    
  43.                     trayIcon.displayMessage("Action Event",     
  44.                             "An Action Event Has Been Peformed!",    
  45.                             TrayIcon.MessageType.INFO);    
  46.                 }    
  47.             };    
  48.   
  49.             trayIcon.setImageAutoSize(true);    
  50.             trayIcon.addActionListener(actionListener);    
  51.   
  52.             try {    
  53.                 tray.add(trayIcon);    
  54.             } catch (AWTException e1) {    
  55.                 e1.printStackTrace();    
  56.             }    
  57.   
  58.         }   
  59.     }  
  60.       
  61.     public static void main(String[] args)  {    
  62.         new Monitor();    
  63.     }    
  64.   
  65. }    


上面是一个鼠标监听的日志文件

阅读更多

没有更多推荐了,返回首页