Backgroud
原理很簡(jiǎn)單:robot類模擬鍵盤輸入,快捷鍵打開微信,搜索好友,把發(fā)送內(nèi)容發(fā)送到粘貼板實(shí)現(xiàn)。
程序源碼
package com.cloudansys.test;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.KeyEvent;
public class T5 {
public static void main(String[] args) throws InterruptedException {
// 好友昵稱
// String friendNickName = "文件傳輸助手";
String friendNickName = "不器";
searchMyFriendAndSend(friendNickName);
}
private static void searchMyFriendAndSend(String friendNickName) throws InterruptedException {
// 創(chuàng)建Robot對(duì)象
Robot robot = getRobot();
//打開微信 Ctrl+Alt+W
assert robot != null;
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_ALT);
robot.keyPress(KeyEvent.VK_W);
//釋放Ctrl按鍵,像Ctrl,退格鍵,刪除鍵這樣的功能性按鍵,在按下后一定要釋放
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.keyRelease(KeyEvent.VK_ALT);
// 該延遲不能少,否則無(wú)法搜索
robot.delay(1000);
// Ctrl + F 搜索指定好友
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_F);
robot.keyRelease(KeyEvent.VK_CONTROL);
// 將好友昵稱發(fā)送到剪切板
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(friendNickName);
clip.setContents(tText, null);
// 以下兩行按下了ctrl+v,完成粘貼功能
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(1000);
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(1000);
// 發(fā)送消息
sendMsg();
}
private static void sendMsg() throws InterruptedException {
String[] mottoes = {
"我只愛你四天,春天夏天秋天冬天!",
"我只愛你三天,昨天,今天,明天!",
"我只愛你兩天,白天,黑天!",
"我只愛你一天,每一天!",
"[玫瑰]愛你么么噠!",
"[呲牙][壞笑]",
"[奸笑]"
};
for (String motto : mottoes) {
sendOneMsg(motto);
}
Thread.sleep(2000);
sendOneMsg("[得意]就問(wèn)你,膩不膩害!");
}
private static void sendOneMsg(String msg) {
// 創(chuàng)建Robot對(duì)象
Robot robot = getRobot();
Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
// 將字符串復(fù)制到剪切板
Transferable tText = new StringSelection(msg);
clip.setContents(tText, null);
// 以下兩行按下了ctrl+v,完成粘貼功能
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_V);
robot.keyRelease(KeyEvent.VK_CONTROL);
// 回車發(fā)送
robot.keyPress(KeyEvent.VK_ENTER);
robot.delay(1000);
}
private static Robot getRobot(){
// 創(chuàng)建Robot對(duì)象
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
return robot;
}
}
效果如下圖所示
在這里插入圖片描述