自制java工具实现 ctrl+c+c 翻译鼠标选中文本

时间:2025-04-02 09:26:31
import cn.hutool.core.text.UnicodeUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; import com.github.kwhat.jnativehook.GlobalScreen; import com.github.kwhat.jnativehook.NativeHookException; import com.github.kwhat.jnativehook.keyboard.NativeKeyEvent; import com.github.kwhat.jnativehook.keyboard.NativeKeyListener; import com.icepeach.Utils.ClipBoardUtil; import com.icepeach.Utils.GUI.MyWindow; public class GlobalKeyListenerExample implements NativeKeyListener { String key = ""; private static final String APP_ID = "你的appid"; private static final String SECURITY_KEY = "你的密钥"; TransApi api = new TransApi(APP_ID, SECURITY_KEY); MyWindow window = new MyWindow(); public void nativeKeyPressed(NativeKeyEvent e) { if ("Ctrl".equals(NativeKeyEvent.getKeyText(e.getKeyCode()))) { key = new String("Ctrl"); } else { key += NativeKeyEvent.getKeyText(e.getKeyCode()); } if ("CtrlCC".equals(key)) { window.setVisible(true); //打印剪切板内容 System.out.println("剪切板内容为:" + ClipBoardUtil.getClipboardText()); //调用翻译接口 String jsonStr = api.getTransResult(ClipBoardUtil.getClipboardText(), "auto", "zh"); // 解析JSON字符串 JSONObject jsonObject = JSONUtil.parseObj(jsonStr); // 获取trans_result数组中的第一个元素 JSONObject transResult = jsonObject.getJSONArray("trans_result").getJSONObject(0); // 获取dst中的内容并转换成中文 String dst = transResult.getStr("dst"); String chineseDst = UnicodeUtil.toString(dst); System.out.println("翻译:"+chineseDst); window.clearText(); window.writeText("剪切板内容为:" + ClipBoardUtil.getClipboardText()); window.writeText("翻译:"+chineseDst); } if (e.getKeyCode() == NativeKeyEvent.VC_ESCAPE) { try { GlobalScreen.unregisterNativeHook(); } catch (NativeHookException nativeHookException) { nativeHookException.printStackTrace(); } } } public void nativeKeyReleased(NativeKeyEvent e) { // ("Key Released: " + (())); } public void nativeKeyTyped(NativeKeyEvent e) { // ("Key Typed: " + (())); } public static void main(String[] args) { try { GlobalScreen.registerNativeHook(); } catch (NativeHookException ex) { System.err.println("There was a problem registering the native hook."); System.err.println(ex.getMessage()); System.exit(1); } GlobalScreen.addNativeKeyListener(new GlobalKeyListenerExample()); } }