Java 实现全局(全操作系统)的鼠标和键盘监控,使用的是SWT Win32 Extension 项目,在以前若使用Java恐怕是很难实现的!
SWT Win32 Extension 让Java拥有了许多对操作系统底层操作的功能!
注:本程序需要SWT Win32 Extension支持?
以下两个例子是:
(一)鼠标Hook
import org.sf.feeling.swt.win32.extension.hook.Hook;import org.sf.feeling.swt.win32.extension.hook.data.HookData;import org.sf.feeling.swt.win32.extension.hook.data.MouseHookData;import org.sf.feeling.swt.win32.extension.hook.listener.HookEventListener; public class HotMouse { public static void main(String[] args) { Hook.MOUSE.addListener(new HookEventListener() { public void acceptHookData(HookData hookData) { if (hookData != null) { //System.out.println("Mouse Point X = " + ((MouseHookData)hookData).getPointX()); //System.err.println("Mouse Point Y =" + ((MouseHookData)hookData).getPointY()); System.err.println(((MouseHookData)hookData).getPointX()+"," + ((MouseHookData)hookData).getPointY()); } if (hookData.getWParam() == 513) { System.out.println("left button pressed");// left button pressed } else if (hookData.getWParam() == 514) { System.out.println("left button released");// left button released } else if (hookData.getWParam() == 516) { System.out.println("right button pressed");// right button pressed } else if (hookData.getWParam() == 517) { System.out.println("right button");// right button } else if (hookData.getWParam() == 519) { System.out.println("middle button 519");// middle button } else if (hookData.getWParam() == 520) { System.out.println("middle button 520");// middle button } } }); Hook.MOUSE.install(); } }
(二)键盘Hook
import org.sf.feeling.swt.win32.extension.hook.Hook;import org.sf.feeling.swt.win32.extension.hook.data.HookData;import org.sf.feeling.swt.win32.extension.hook.data.KeyboardHookData;import org.sf.feeling.swt.win32.extension.hook.listener.HookEventListener; public class HotKey { public static void main(final String[] args) { Hook.KEYBOARD.addListener(new HookEventListener(){//@Override public void acceptHookData(HookData arg0) { KeyboardHookData KHD = ((KeyboardHookData)arg0); System.out.println(KHD.getWParam()+" - "+KHD.getTransitionState()); //Print code if( KHD.getScanCode() == 29 && KHD.getTransitionState()){ //按下Ctrl執行動作 System.out.println("Hotting"); }else if( KHD.getScanCode() == 1 ){ //按下[ESC]結束 System.exit(0); } }}); Hook.KEYBOARD.install(); //註冊事件 }}
以上两个例子源于: 这里要感谢!感谢!