Java for mouse and keyboard action background monitoring

Source: Internet
Author: User

Sometimes we need to monitor the mouse and keyboard movements (mouse movement, keyboard click), such as key record, mouse coordinate record.

We use JNA to achieve the above operation

 tips:jna class Library uses a very small local class library sub dynamic call to Local code Java interface local code The structure of the method and some basic properties. This saves a lot of configuration and compilation code to fit multiple platforms. This is because the interfaces in the public jar package provided by JNA are called.

First we implement the following code to monitor the mouse

Package Getinfo;import Java.io.bufferedwriter;import Java.io.file;import java.io.filewriter;import Java.io.ioexception;import Java.text.simpledateformat;import Java.util.date;import Com.sun.jna.Structure;import Com.sun.jna.examples.win32.kernel32;import Com.sun.jna.examples.win32.user32;import Com.sun.jna.examples.win32.user32.hhook;import Com.sun.jna.examples.win32.user32.msg;import Com.sun.jna.examples.win32.w32api.hmodule;import Com.sun.jna.examples.win32.w32api.lresult;import Com.sun.jna.examples.win32.w32api.wparam;import Com.sun.jna.examples.win32.user32.hookproc;public class MouseHook Implements runnable{public static final int wm_mousemove = 512;private static hhook hhk;private static Lowlevelmouseproc m Ousehook;final static User32 lib = User32.instance;private Boolean [] On_off=null;public Mousehook (Boolean [] on_off) {thi S.on_off = On_off;} Public interface Lowlevelmouseproc extends HOOKPROC {LRESULT callback (int nCode, WPARAM WPARAM, MouseHookStruct lParam);} public static ClasS MouseHookStruct extends Structure {public static class Byreference extends MouseHookStruct implementsstructure.byreference {};p ublic user32.point pt;public int whittestcode;public User32.ULONG_PTR dwExtraInfo ;} public void Run () {hmodule hmod = Kernel32.INSTANCE.GetModuleHandle (null), Mousehook = new Lowlevelmouseproc () {public lre Sult Callback (int nCode, WPARAM wparam,mousehookstruct info) {SimpleDateFormat df1 = new SimpleDateFormat ("Yyyy-mm-dd"); SimpleDateFormat DF2 = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Filename=df1.format (New Date ()); String Time=df2.format (New Date ()); BufferedWriter Bw1=null; BufferedWriter bw2=null;try {bw1=new bufferedwriter (new FileWriter (".//log//" +filename+ "_mouse.txt"), true) ); bw2=new BufferedWriter (New FileWriter (".//log//" +filename+ "_common.txt"), true);} catch (IOException e) {e.printstacktrace ();} if (on_off[0] = = False) {system.exit (0);} if (nCode >= 0) {switch (Wparam.intvalue ()) {case MouseHook.WM_MOUSEMOVE:try {Bw1.writE (time+ "# # #" + "x=" + info.pt.x+ "y=" + info.pt.y+ "\ r \ n"), Bw2.write (time+ "# # #" + "x=" + info.pt.x+ "y=" + info.pt. y+ "\ r \ n"); Bw1.flush (); Bw2.flush ();} catch (IOException e) {e.printstacktrace ();}}} Return lib. CallNextHookEx (HHK, NCode, WParam, Info.getpointer ());}; HHK = lib. SetWindowsHookEx (User32.wh_mouse_ll, Mousehook, Hmod, 0); int result; msg msg = new MSG (); while (result = lib. GetMessage (msg, NULL, 0, 0))! = 0) {if (result = =-1) {System.err.println ("Error in Get Message"); break;} else {System.err . println ("got Message"); Lib. TranslateMessage (msg); Lib. DispatchMessage (msg);}} Lib. UnhookWindowsHookEx (HHK);}}
Ability to output the coordinates of the mouse while the mouse is moving

Next is the code that listens to the keyboard

Package Getinfo;import Java.io.bufferedwriter;import Java.io.file;import java.io.filewriter;import Java.io.ioexception;import Java.text.simpledateformat;import Java.util.date;import Com.sun.jna.examples.win32.kernel32;import Com.sun.jna.examples.win32.user32;import Com.sun.jna.examples.win32.user32.hhook;import Com.sun.jna.examples.win32.user32.kbdllhookstruct;import Com.sun.jna.examples.win32.user32.lowlevelkeyboardproc;import Com.sun.jna.examples.win32.user32.msg;import Com.sun.jna.examples.win32.w32api.hmodule;import Com.sun.jna.examples.win32.w32api.lresult;import Com.sun.jna.examples.win32.w32api.wparam;public class Keyboardhook implements runnable{private static HHOOK hhk; private static LowLevelKeyboardProc keyboardhook;final static User32 lib = User32.instance;private Boolean [] On_off=null ;p ublic Keyboardhook (Boolean [] on_off) {this.on_off = On_off;} public void Run () {hmodule hmod = Kernel32.INSTANCE.GetModuleHandle (null); Keyboardhook = new LowLevelKeyboardProc () { Public LresulT callback (int nCode, WPARAM WPARAM, kbdllhookstruct info) {SimpleDateFormat df1 = new SimpleDateFormat ("Yyyy-mm-dd"); SimpleDateFormat DF2 = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Filename=df1.format (New Date ()); String Time=df2.format (New Date ()); BufferedWriter Bw1=null; BufferedWriter bw2=null;try {bw1=new bufferedwriter (new FileWriter (".//log//" +filename+ "_keyboard.txt"), true); Bw2=new BufferedWriter (New FileWriter (".//log//" +filename+ "_common.txt"), true);} catch (IOException e) {e.printstacktrace ();} if (on_off[0] = = False) {system.exit (0);} try {bw1.write (time+ "# # #" +info.vkcode+ "\ r \ n"), Bw2.write (time+ "# # #" +info.vkcode+ "\ r \ n"); Bw1.flush (); Bw2.flush ( );} catch (IOException e) {e.printstacktrace ();} Return lib. CallNextHookEx (HHK, NCode, WParam, Info.getpointer ());}; HHK = lib. SetWindowsHookEx (User32.wh_keyboard_ll, Keyboardhook, Hmod, 0); int result; msg msg = new MSG (); while (result = lib. GetMessage (msg, NULL, 0, 0)) = = 0) {if (result = =-1) {System. ERR.PRINTLN ("Error in Get Message"); else {System.err.println ("got Message"); Lib. TranslateMessage (msg); Lib. DispatchMessage (msg);}} Lib. UnhookWindowsHookEx (HHK);}}

Finally, the code that gets the process information

Package Getinfo;import Java.io.bufferedreader;import Java.io.bufferedwriter;import java.io.file;import Java.io.filewriter;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.text.SimpleDateFormat; Import Java.util.date;public class ProcessInfo implements Runnable{private Boolean [] on_off=null;public ProcessInfo ( Boolean [] on_off) {this.on_off = On_off;} public void Run () {BufferedReader input = null; Process process = NULL; BufferedWriter Bw=null; SimpleDateFormat df1 = new SimpleDateFormat ("Yyyy-mm-dd"); SimpleDateFormat DF2 = new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"); String Filename=null; String Time=null;try {while (on_off[0]) {Filename=df1.format (new date ()); Time=df2.format (new Date ()); bw=new BufferedWriter (New FileWriter (New File (".//log//" +filename+ "_processinfo.txt"), true)); Thread.Sleep (60000);p rocess = Runtime.getruntime (). EXEC ("cmd.exe/c tasklist"); input =new BufferedReader (new Inputstr Eamreader (Process.getinputstream ())); String line = ""; int I=0;input.readlINE (); Input.readline (); Input.readline (); while (line = Input.readline ()) = null) {Bw.write (time+ "# # #" +line+ "\ r \ n") ; Bw.flush (); i++;}}} catch (Exception e) {e.printstacktrace ();} finally{try {bw.close (); Input.close ();} catch (IOException e) { E.printstacktrace ();}}}

Class that opens the thread above

Package Getinfo;import java.awt.AWTException;  Import Java.awt.Image;  Import Java.awt.MenuItem;  Import Java.awt.PopupMenu;  Import Java.awt.SystemTray;  Import Java.awt.Toolkit;  Import Java.awt.TrayIcon;  Import java.awt.event.ActionEvent;  Import Java.awt.event.ActionListener; public class Monitor {public Monitor () {Boolean [] on_off={true};new Thread (new ProcessInfo (On_off)). Start (); New THR  EAD (New Keyboardhook (On_off)). Start (); New Thread (New Mousehook (On_off)). Start (); final TrayIcon TrayIcon;  if (systemtray.issupported ()) {Systemtray tray = Systemtray.getsystemtray ();  Image image = Toolkit.getdefaulttoolkit (). GetImage (".//lib//monitor.png"); ActionListener Exitlistener = new ActionListener () {public void actionperformed (ActionEvent e) {System.out.println ("Ex  Iting ... ");  System.exit (0);  }};  PopupMenu popup = new PopupMenu ();  MenuItem Defaultitem = new MenuItem ("Exit");  Defaultitem.addactionlistener (Exitlistener);  Popup.add (Defaultitem); TrayIcon = new TrayIcon(Image, "Monitor", popup); ActionListener ActionListener = new ActionListener () {public void actionperformed (ActionEvent e) {trayicon.displaymess  Age ("Action event", "A action event has Been peformed!", TrayIcon.MessageType.INFO);  }  };  Trayicon.setimageautosize (TRUE);  Trayicon.addactionlistener (ActionListener);  try {tray.add (TrayIcon);  } catch (Awtexception E1) {e1.printstacktrace ();  }}}public static void Main (string[] args) {new Monitor ();   }  }


Above is a log file for mouse monitoring

Java for mouse and keyboard action background monitoring

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.