基于AutoHotkey方便翻译器SmartTranslator
- 用AHK智能翻译器支持的智能翻译器
-
-
- 1.API接口
- 2.功能简述
- 3.使用方法
- 4.操作演示
- 5.源代码
- 6.下载软件和代码
- 词典界面:海词、词霸、有道。
- 翻译界面:谷歌、百度、有道。
- 无需设置源语言和目标语言,支持中英文自动识别
- 支持句子和单词的自动识别,无需其他切换操作
- 未完待续···
- 第一步:选择需要查询的单词或者需要翻译的句子
- 第二步:长按右键(或按快捷键)window c )直接查单词或翻译
- 第三步:翻译完成后,将翻译结果显示在鼠标附近的弹出窗口上。鼠标放在文本上,弹出窗口永远不会消失。离开弹出窗口一秒钟后,窗口会自动关闭
- 第四步:按下翻译结果文本上的左键,替换当前翻译内容;按右键,将结果复制到剪贴板上

;@Ahk2Exe-SetMainIcon Icon\SmartTranslator.ico ;@Ahk2Exe-AddResource Icon\SmartTranslator.ico, 160 ;@Ahk2Exe-SetProductName SmartTranslator ;托盘图标不显示 ;#NoTrayIcon ;跳过对话框, 旧例子的自动替换 #SingleInstance force ;设置工作目录 SetWorkingDir %A_ScriptDir% ;不检查空变是否为环境变量 #NoEnv ;在可能出现错误的特定情况下启用或禁用警告, 比如写错或者缺乏全局声明 ;#Warn ;让脚本保持后台运行 #Persistent ;防止用户的键与发送的键穿插在一起 SendMode Input /* **********************************include Start******************************************* */ #include WinHttpRequests.ahk #include TranslateAPI.ahk #Include <Basic> /* **********************************include End********************************************* */ /* **********************************Global start********************************************* */ Global TranslateResults := "Welcome to the SmartTranslator" /* **********************************global End********************************************* */ /* **********************************Init Code Start******************************************* */ ShowWizard() ConfingInit() TrayInit()
return
/* **********************************Init Code End********************************************* */
/* **********************************User Code Start******************************************* */
#c::
ClipboardAnalyze()
return
$RButton::
KeyWait, RButton, T0.25
if (ErrorLevel = 1)
ClipboardAnalyze()
else
Send, {
RButton}
Return
ClipboardAnalyze()
{
Global
clipboard := ""
send ^{
c}
ClipWait, 1
Clipboard := StrReplace(Clipboard, "`r`n", " ")
if RegExMatch(clipboard, "[一-鬼]") ;查找汉字.
{
;中文模式
dictOut := StrReplace(Clipboard, A_Tab)
dictOut := StrReplace(dictOut, A_Space)
if (strlen(dictOut) >3 || RegExMatch(dictOut, "[^一-鬼]") != 0 )
{
;翻译模式
TranslateResults := Select_Dict_Trans("Trans",dictOut)
}
Else
{
;词典模式
TranslateResults := Select_Dict_Trans("Dict",dictOut)
if(strlen(Results) = 0)
TranslateResults := Select_Dict_Trans("Trans",dictOut)
}
}
else
{
;英文模式
dictOut := StrReplace(Clipboard, A_Tab)
pos := RegExMatch(dictOut, "\s")
pos += 1
;查找是否含有字母、空格之外的符号
if (RegExMatch(dictOut, "[^a-zA-Z\s]", var) || RegExMatch(dictOut, "\s",, pos))
{
;翻译模式
TranslateResults := Select_Dict_Trans("Trans",dictOut)
}
Else
{
;词典模式
TranslateResults := Select_Dict_Trans("Dict",dictOut)
if(strlen(TranslateResults)=0)
TranslateResults := Select_Dict_Trans("Trans",dictOut)
}
}
GuiTip(TranslateResults)
Clipboard := ""
return
}
/* **********************************User Code End********************************************* */
/* **********************************Gui Code Start********************************************* */
/* GUI内容显示 */
;@Ahk2Exe-Bin ,,"UTF-8"
GuiTip(message := "Welcome to use the SmartTranslator!")
{
Global varText := message
If (StrLen(message)>=300)
{
W_0 := "w950"
}
Else If (StrLen(message)>=100)
{
W_0 := "w700"
} Else If (StrLen(message)>=55)
{
W_0 := "w500"
} Else
W_0 := ""
Gui, GuiTip:Destroy
Gui, GuiTip:+ToolWindow +HwndGuiTip_A -Caption +AlwaysOnTop border -DPIScale
Gui, GuiTip:Color, cDDDDDD
Gui, GuiTip:Font, s13 c2D2D2D Q5, 微软雅黑
Gui, GuiTip:Margin, 5, 5
Gui, GuiTip:Add, Text, X0 %W_0% gGuiTipText, %message%
Gui, GuiTip:Font, s10 c333333 Q5, 微软雅黑
CoordMode, Mouse
MouseGetPos, Mu_XX, Mu_YY
Gui_XX := Mu_XX+10, Gui_YY := Mu_YY+10
Gui, GuiTip:Show, x%Gui_XX% y%Gui_YY%,GuiTip
Gui, GuiTip:Show, x%Gui_XX% y%Gui_YY%,GuiTip
SetTimer, GUISet, -1000
}
return
/* 替换动作
标签(左键) */
GuiTipText:
ToolTip, 原文已被替换
SetTimer, Move_TT, -500
Gui, GuiTip:Destroy
Clipboard := varText
Send ^{
v}
Sleep, 100
Clipboard := ""
return
/* 复制动作标签(右键) */
GuiTipGuiContextMenu:
ToolTip, 译文已被复制
SetTimer, Move_TT, -500
Gui, GuiTip:Destroy
Clipboard := varText
return
/* GUI窗口管理,悬浮则保持,离开则关闭 */
GuiSet:
MouseGetPos, mx,my
WinGetPos, wx, wy, wd, wh,GuiTip
if((mx < wd) && (my < wh))
{
SetTimer, GUISet, -500
}
Else
{
Gui, GuiTip:Destroy
}
Return
/* 关闭提示 */
Move_TT()
{
ToolTip
Return
}
/* **********************************Gui Code End********************************************* */
/* 调用翻译和词典接口 */
Select_Dict_Trans(mode:= "Trans",str := "hello")
{
if(mode = "Dict")
{
DictChoice := Ini.Read("BasicSetting","DictChoice")
if(DictChoice = 1)
TheResults := Dict.Dict(str)
if(DictChoice = 2)
TheResults := Dict.Youdao(str)
if(DictChoice = 3)
TheResults := Dict.Ciba(str)
}
if(mode = "Trans")
{
TransChoice := Ini.Read("BasicSetting","TransChoice")
if(TransChoice = 1)
TheResults := Trans.Google(str)
if(TransChoice = 2)
TheResults := Trans.Youdao(str)
if(TransChoice = 3)
TheResults := Trans.Baidu(str)
}
return TheResults
}
/* 初始化配置文件 */
ConfingInit()
{
if !(FileExist("config.ini"))
{
Ini.Write("BasicSetting","StartUp",False)
Ini.Write("BasicSetting","DictChoice",3)
Ini.Write("BasicSetting","TransChoice",3)
}
}
/* 托盘菜单初始化 */
TrayInit()
{
Menu, Tray, NoStandard
Menu, Tray, Add, 设置, TraySetting
Menu, Tray, Default, 设置
Menu, Tray, Add, 关于, TrayAbout
Menu, Tray, Add, 退出, TrayExit
IniRead, OnStart, config.ini, Setting, StartUp ,0"
if(OnStart = 1)
Menu, Tray, Check, 开机自启
return
}
/* 软件设置 */
TraySetting()
{
Global
DictChoice := Ini.Read("BasicSetting","DictChoice")
TransChoice := Ini.Read("BasicSetting","TransChoice")
StartUpCheck := Ini.Read("BasicSetting","StartUp")
Gui SettingGui:New
Gui SettingGui:-MaximizeBox -MinimizeBox
GUi SettingGui:Font, s10, Verdana
Gui SettingGui:Add, GroupBox, w375 h100, 基本设置
GUi SettingGui:Add, Text, X20 Y35, 词典引擎
Gui SettingGui:Add, DropDownList, X80 Y35 W70 vDictChoice AltSubmit Choose%DictChoice%, 海词|词霸|有道
GUi SettingGui:Add, Text,X20 Y70, 翻译引擎
Gui SettingGui:Add, DropDownList, X80 Y70 W70 vTransChoice AltSubmit Choose%TransChoice%, 百度|谷歌|有道
Gui SettingGui:Add, Checkbox, X200 Y35 vStartUpBtn Checked%StartUpCheck%, 开机自启动
Gui SettingGui:Add, GroupBox, X12 Y110 w375 h150, 高级设置
GUi SettingGui:Add, Button, X80 Y268 W60 gSettingGuiOK, 确定
GUi SettingGui:Add, Button, X160 Y268 W60 gSettingGuiCancel, 取消
GUi SettingGui:Add, Button, X240 Y268 W60 gSettingGuiApply, 应用
Gui SettingGui:Show, W400 H300 Center, 设置
return
SettingGuiOK:
SettingGuiApply:
GUi SettingGui:Submit
Ini.Write("BasicSetting","StartUp",False)
Ini.Write("BasicSetting","DictChoice",DictChoice)
Ini.Write("BasicSetting","TransChoice",TransChoice)
SetStartup(StartUpBtn)
Ini.Write("BasicSetting","StartUp",StartUpBtn)
return
SettingGuiCancel:
Gui SettingGui:Destroy
return
}
/* 设置开机自启动 */
SetStartup(State)
{
StratName := StrReplace(StrReplace(A_ScriptName,".ahk"),".exe")
if(State)
{
RegRead, RegVar, HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, %StratName%
if(ErrorLevel = 1)
{
RegWrite, REG_SZ, HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, %StratName%, %A_ScriptFullPath%
TrayTip,,已设置开机自启!,1,1
}
}
else
{
RegRead, RegVar, HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, %StratName%
if(ErrorLevel = 0)
{
RegDelete, HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Run, %StratName%
TrayTip,,已取消开机自启!,1,1
}
}
return
}
/* 关于软件 */
TrayAbout()
{
MsgBox ,,关于,by 冷月风华!
return
}
/* 退出软件 */
TrayExit()
{
ExitApp
}
ShowWizard()
{
if !(FileExist("config.ini"))
{
MsgBox ,,使用帮助,
(
欢迎使用SmartTranslator翻译小助手!初次使用,先看一下使用方法吧!
一、选择文本后,使用默认快捷键win+c或长按右键进行查词和翻译。
二、软件查词\翻译完成后,左键文本可以用译文替换当前所选,右键文
本可以复制译文。
)
}
}
#include WinHttpRequests.ahk
#Include <Basic>
Class Dict
{
Dict(wd := "hello")
{
DictDictionaryAPI := "https://apii.dict.cn/mini.php?q="
DictUrl := DictDictionaryAPI . URLEncode(wd)
TranslateRes := UrlDownloadToVar(DictUrl, "GET")
if TranslateRes = -1
return "网络异常"
RegExMatch(TranslateRes,"(?<=id=""e"">).*?(?=</div><br><div)",res)
return StrReplace(res, "<br>", "`r`n")
}
Youdao(wd := "hello")
{
YoudaoDictionaryAPI := "https://dict.youdao.com/suggest?num=1&doctype=json&q="
YoudaotUrl := YoudaoDictionaryAPI . URLEncode(wd)
TranslateRes := UrlDownloadToVar(YoudaotUrl, "GET")
if TranslateRes = -1
return "网络异常"
RegExMatch(TranslateRes,"(?<=explain"":"").*?(?="",""entry)",res)
s := RegExMatchAll(res,"\w+\.")
for index,each in s
{
if index != 1
{
res := StrReplace(res, each, "`r`n" . each)
}
}
res := StrReplace(res, "...")
res:= StrReplace(res, "`r`n`r`n", "`r`n")
return res
}
Ciba(wd := "hello")
{
;c := RegExMatch(wd, "[^\x00-\xff]+")
CibaDictionaryAPI := "http://dict-co.iciba.com/search.php?word="
CibaUrl := CibaDictionaryAPI . URLEncode(wd)
TranslateRes := UrlDownloadToVar(CibaUrl, "GET")
if TranslateRes = -1
return "网络异常"
RegExMatch(TranslateRes,"(?<=<br><br>`n).* <br",res)
res := StrReplace(res," ")
res := StrReplace(res,"<br />","`n")
return StrReplace(res,"<br","")
}
}
Class Trans
{
Google(wd := "Hello World!")
{
wd := StrReplace(wd, "`r"), wd := StrReplace(wd, "`n")
sl := RegExMatch(wd, "[^\x00-\xff]+") ? "zh-CN" : "en" ;查找汉字
tl := (sl = "zh-CN") ? "en" : "zh-CN"
GoogleTranslatorAPI := "https://translate.googleapis.com/translate_a/single?client=gtx&dt=t"
GoogleUrl := GoogleTranslatorAPI . "&sl=" . sl . "&tl=" . tl . "&q=" . URLEncode(wd
TranslateRes := UrlDownloadToVar(GoogleUrl, "GET")
if TranslateRes = -1
return "网络异常"
TranslateRes := StrReplace(StrReplace(TranslateRes,"[[]],[[[",""), "[", "#")
ResArray := RegExMatchAll(TranslateRes,"(?<=#"").*?(?=""`,"")")
return ArrayToString(ResArray," ")
}
Youdao(wd := "Hello World!")
{
wd := StrReplace(wd, "`r"), wd := StrReplace(wd, "`n")
YoudaoTranslatorAPI := "https://fanyi.youdao.com/translate?&doctype=json&type=AUTO&i="
YoudaoUrl := YoudaoTranslatorAPI . URLEncode(wd)
TranslateRes := UrlDownloadToVar(YoudaoUrl, "GET")
if TranslateRes = -1
return "网络异常"
ResArray := RegExMatchAll(TranslateRes,"(?<=tgt"":"").*?(?=""})")
res := ArrayToString(ResArray," ")
return StrReplace(res, "\u201D")
}
Baidu(wd := "hello world!")
{
wd := StrReplace(wd, "`r"), wd := StrReplace(wd, "`n")
BaiduTranslatorAPI := "https://fanyi.baidu.com/transapi?&source=txt"
from := RegExMatch(wd, "[^\x00-\xff]+") ? "zh" : "en" ;查找汉字
to := (from = "en") ? "zh" : "en"
query := URLEncode(wd)
BaiduUrl := BaiduTranslatorAPI . "&from="
标签: 高压电阻器5w500mw70继电器