Thực hiện chuột và bàn phím không dây bằng TCP và luồng đa nhiệm - Robot

Khi ứng dụng Windows nhận được tín hiệu điều khiển từ thiết bị Android, lớp java.awt.Robot sẽ được sử dụng để mô phỏng hành động chuột và bàn phím. Dưới đây là cách triển khai chi tiết:

public static Robot robotCtrl;

Khởi tạo đối tượng Robot trong hàm khởi tạo:

// Khởi tạo Robot
try {			
    robotCtrl = new Robot();			
} catch (AWTException e) {		
    l_status.setText("Lỗi: " + e.getMessage());			
}

Hàm xử lý lệnh đầu vào:

// Xử lý điều khiển
public static void processInput(String commandStr) {
    String[] cmdParts = commandStr.split("/");
    
    // Di chuyển chuột
    if (isNumeric(cmdParts[0])) {			
        Point currentPos = MouseInfo.getPointerInfo().getLocation();
        robotCtrl.mouseMove(
            currentPos.x + Integer.parseInt(cmdParts[0]), 
            currentPos.y + Integer.parseInt(cmdParts[1])
        );			
    }
    // Xử lý nút chuột
    else if (cmdParts[0].equals("b")) {			
        if (cmdParts[1].equals("l")) {
            robotCtrl.mousePress(InputEvent.BUTTON1_DOWN_MASK);
            robotCtrl.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
        }
        if (cmdParts[1].equals("r")) {
            robotCtrl.mousePress(InputEvent.BUTTON3_DOWN_MASK);
            robotCtrl.mouseRelease(InputEvent.BUTTON3_DOWN_MASK);
        }			
    }
    // Xử lý phím bấm
    else if (cmdParts[0].equals("k")) {
        int keyCode = getKeyCode(cmdParts[1]);
        if (keyCode != -1) {
            robotCtrl.keyPress(keyCode);
            robotCtrl.keyRelease(keyCode);
        }
    }
}

Hàm hỗ trợ xác định mã phím:

private static int getKeyCode(String keyChar) {
    switch (keyChar) {
        case "a": return KeyEvent.VK_A;
        case "b": return KeyEvent.VK_B;
        case "c": return KeyEvent.VK_C;
        case "d": return KeyEvent.VK_D;
        case "e": return KeyEvent.VK_E;
        case "f": return KeyEvent.VK_F;
        case "g": return KeyEvent.VK_G;
        case "h": return KeyEvent.VK_H;
        case "i": return KeyEvent.VK_I;
        case "j": return KeyEvent.VK_J;
        case "k": return KeyEvent.VK_K;
        case "l": return KeyEvent.VK_L;
        case "m": return KeyEvent.VK_M;
        case "n": return KeyEvent.VK_N;
        case "o": return KeyEvent.VK_O;
        case "p": return KeyEvent.VK_P;
        case "q": return KeyEvent.VK_Q;
        case "r": return KeyEvent.VK_R;
        case "s": return KeyEvent.VK_S;
        case "t": return KeyEvent.VK_T;
        case "u": return KeyEvent.VK_U;
        case "v": return KeyEvent.VK_V;
        case "w": return KeyEvent.VK_W;
        case "x": return KeyEvent.VK_X;
        case "y": return KeyEvent.VK_Y;
        case "z": return KeyEvent.VK_Z;
        case " ": return KeyEvent.VK_SPACE;
        default: return -1;
    }
}

Thẻ: Java robot-class tcp-ip multithreading

Đăng vào ngày 24 tháng 6 lúc 09:48