最近在做一個軟工的屏幕監控軟件,已經實現了屏幕圖片的傳輸,但是沒有鼠標,才發現鍵盤上的PtrScSysRq鍵所截到圖是沒有鼠標信息的。==
暫時只需實現鼠標的移動事件,用robot.mouseMove(x,y)函數實現,所以就沒有用到MouseEvent對象,用了MouseInfo類中的getPointerInfo()方法。
且需知道在Swing程序中,通常通過鼠標事件的MouseEvent對象,來獲取鼠標的坐標,而這種情況只能在窗體事件中獲取(參考Java通過MouseInfo獲取鼠標位置)
程序分為控制端與被控制端,在兩臺pc上運行。
控制端
import java.awt.MouseInfo;import java.awt.Point;import java.io.DataOutputStream;import java.io.IOException;import java.net.ServerSocket;import java.net.Socket;//教師端把 鼠標的信息發給 學生端口public class SendMouseMessage extends Thread{PRivate int OperaTE_PORT = 8001;private ServerSocket server;private Socket socket;private String operateStr;public static void main(String[] args){new SendMouseMessage().start();}public SendMouseMessage(){try {server = new ServerSocket(OPERATE_PORT);//JOptionPane.showMessageDialog(null, "已經開始監聽");} catch (IOException e1) {e1.printStackTrace();}}//多線程 在無線的循環中監聽客戶端的public void run(){while(true){Point point = MouseInfo.getPointerInfo().getLocation(); //operateStr ="Movemouse,"+point.x+","+point.y;try {socket = server.accept();socket.setSoTimeout(1000000);DataOutputStream output =new DataOutputStream(socket.getOutputStream());output.write(operateStr.getBytes());output.flush(); //刷行輸出流,并且使所有緩沖的輸出字節寫出output.close(); //關閉輸出流且釋放資源System.out.println("INFO: "+operateStr);} catch (IOException e) {System.out.println("已經停止連接");break; //斷開連接的時候就停止無線循環}/*try {Thread.sleep(100);System.out.println("停止100微秒");} catch (InterruptedException e) {e.printStackTrace();}*/}}}
被控端
import java.awt.AWTException;import java.awt.Robot;import java.io.DataInputStream;import java.io.IOException;import java.net.Socket;/* * 學生端 控制鼠標和教師端一致 * 該類 負責接收鼠標的信息 并且用robot.mouseMove()函數控制鼠標移動 */public class OperateMouse implements Runnable{public static void main(String[] args){new Thread(new OperateMouse()).start();}private Socket socket;private int OPERATE_PORT = 8001;private Robot robot;@Overridepublic void run() {while(true){try {socket = new Socket("202.116.60.6",OPERATE_PORT);robot = new Robot();DataInputStream dataIn = new DataInputStream(socket.getInputStream()); String info="";int r;while((r=dataIn.read()) != -1){info +=""+(char)r; //把字節數組中所有元素都變為字符型//System.out.println("當前讀到的數據時"+info);}dataIn.close();System.out.println("數據流斷開"+info); if(info!=null){ String s[] = info.trim().split(","); if("Movemouse".equals(s[0].trim()));{if (s.length == 3) {int x = Integer.parseInt(s[1].trim());int y = Integer.parseInt(s[2].trim());System.out.println("輸出鼠標的信息"+x+" "+ y);robot.mouseMove(x, y);}}}} catch (IOException e) {System.out.println("已斷開連接");break;} catch (AWTException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}}新聞熱點
疑難解答