所需依赖:jna-5.4.0.jar 和 jna-platform-5.4.0.jar
下载地址: https://github.com/java-native-access/jna
首先需要将微信置顶层:
WinDef.HWND hwnd = User32.INSTANCE.FindWindow(null, "微信");
if (hwnd == null) {
System.out.println("not running");
} else {
User32.INSTANCE.ShowWindow(hwnd, 9);
User32.INSTANCE.SetForegroundWindow(hwnd); // bring to front
}
使用Robot类 模拟安键输入Ctrl+F和Enter查找指定用户
static Robot robot;
static {
try {
if (robot == null)
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
}
将需要输入的内容复制到裁剪版
public static void copy(String text) {
Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(text);
sysc.setContents(tText, null);
System.out.println("已复制");
}
再通过Robot模拟Ctrl+V,粘贴文字内容,调用 sendCtrlWith(‘v’);
public static void sendCtrlWith(char c) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
robot.keyPress(KeyEvent.VK_CONTROL);
sendKey(c);
robot.keyRelease(KeyEvent.VK_CONTROL);
}
public static void sendKey(char c) {
try {
String KeyName = (c+"").toUpperCase();
Field f = KeyEvent.class.getDeclaredField("VK_" + KeyName);
Object o = f.get(null);
int keyCode = Integer.parseInt(o + "");
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
} catch (Exception e) {
e.printStackTrace();
}
}
转载于:https://blog.csdn.net/csdn_lrx/article/details/96630776