Autohotkey window 下宏键盘、宏命令开发入门

🌾 💐 🌷 🌹

我的AHK下载地址:https://github.com/dragon8github/Pandora/raw/master/pandora.exe

AutoHotKey 下载:https://autohotkey.com/download/

国内自制的ahk网站:https://www.autoahk.com/

推荐下载installer

 

官方网站:https://www.autohotkey.com/docs/AutoHotkey.htm

中文官网:https://wyagd001.github.io/zh-cn/docs/Tutorial.htm

AHK脚本编辑器推荐:http://fincs.ahk4.net/scite4ahk/  |  https://wyagd001.github.io/zh-cn/docs/commands/Edit.htm#Editors

个人推荐使用sublime text作为autohotkey的编辑器,只需要安装aotuhotkey插件即可。

 

常量列表,十分实用:https://wyagd001.github.io/zh-cn/docs/Variables.htm#DD

优秀的脚本合集:https://www.autoahk.com/archives/1444

特殊键解决方案(实用):https://blog.csdn.net/liuyukuan/article/details/5924137   https://wyagd001.github.io/zh-cn/docs/KeyList.htm#SpecialKeys

GUI的一些布局API:https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm#PosSize

使用html做ahk界面:https://blog.csdn.net/liuyukuan/article/details/53504400

 

(重要)使用SciTE4AutoHotkey,出现中文怪异的问题。

 左上角File--Encoding---UTF-8 with BOM

 

1、代码加入 #InstallKeybdHook,并且开启脚本

2、左键点击右下角的图标 -> View -> Key History

将ahk编译成exe:http://ahkcn.sourceforge.net/docs/Scripts.htm#ahk2exe

 

快捷键

SymbolDescription
# Win (Windows logo key)
! Alt
^ Control / Ctrl
+ Shift
& An ampersand may be used between any two keys or mouse buttons to combine them into a custom hotkey. 

默认是左侧的,如果想要右侧的加入< >即可,譬如按下右侧的ctrl , 那就是 >^

更多热键请参考:

(重要,推荐)https://autohotkey.com/docs/Hotkeys.htm

https://autohotkey.com/docs/Hotkeys.htm

https://autohotkey.com/docs/commands/Send.htm

 

AHK DNF 连发 连按

x::
    Send, {LButton Down}
    sleep, 1
    Send, {LButton Up}
return

 

管理员授权,适合大部分游戏

https://github.com/ganlvtech/genshin-impact-ahk/blob/main/原神.ahk

https://github.com/Yiffyi/YuanShen-ahk

; https://stackoverflow.com/questions/43298908/how-to-add-administrator-privileges-to-autohotkey-script
full_command_line := DllCall("GetCommandLine", "str")
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
    try ; leads to having the script re-launching itself as administrator
    {
        if A_IsCompiled
            Run *RunAs "%A_ScriptFullPath%" /restart
        else
            Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
    }
    ExitApp
}

 

 

 原神判断

https://github.com/ganlvtech/genshin-impact-ahk/blob/main/原神.ahk

https://github.com/Yiffyi/YuanShen-ahk

; https://stackoverflow.com/questions/43298908/how-to-add-administrator-privileges-to-autohotkey-script
full_command_line := DllCall("GetCommandLine", "str")
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
    try ; leads to having the script re-launching itself as administrator
    {
        if A_IsCompiled
            Run *RunAs "%A_ScriptFullPath%" /restart
        else
            Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
    }
    ExitApp
}

#IfWinActive ahk_exe YuanShen.exe
; 按住 v 连续攻击,适合肖宫 v:: Send, {LButton Down} sleep,
1 Send, {LButton Up} return

 

 

IfWinNotActive 多个筛选条件 GroupAdd

; IfWinNotActive 多个筛选条件 GroupAdd
GroupAdd, ESC, 神武
GroupAdd, ESC, CityEngine

#IfWinNotActive, ahk_group ESC

WinGetTitle, Title, A
MsgBox, The active window is "%Title%".

#IfWinNotActive

 

 

特殊键,只需要注意第二列

https://wyagd001.github.io/zh-cn/docs/KeyList.htm#SpecialKeys

^+esc::
Send, ^+{vksc029}
return

 

 修改窗口的大小和位置

#!right::
WinGet, OutputVar, MinMax, A
if (OutputVar == 1) {
    WinRestore, A
} else {
    WinMaximize, A
}

WinMove, A, , A_ScreenWidth / 2, 0, A_ScreenWidth / 2, A_ScreenHeight - 80
return

 

 

清空换行符和空格符

fuck(value) {
    return Trim(StrReplace(StrReplace(StrReplace(value, "`r"), "`n"), "`r`n"))
}

 

获取图片大小(根据图片路径)

objImage := ComObjCreate("WIA.ImageFile")
objImage.LoadFile(path)
MsgBox, % objImage.Width
MsgBox, % objImage.Height

 

 

将桌面的图片上传到阿里云图床

http://likeyunba.com/imgupload/

http://thinkai.net/p/561

先引入上述的ahk文件。

; 将里面的 uploadfile 注释掉
#Include src/uploadFile.ahk

; 自定义上传配置
uploadfile(objParam){
    CreateFormData(PostData, hdr_ContentType, objParam)
    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    whr.Open("POST", "https://api.uomg.com/api/image.ali", true) ;地址
    whr.SetRequestHeader("Content-Type", hdr_ContentType)
    whr.Send(PostData)
    whr.WaitForResponse()
    return whr.ResponseText
}



!z::
path := A_Desktop . "\fuckyou.png"

; 注意,这里的路径必须是数组格式。哪怕只有一个。
data := uploadfile({ Filedata: [path], file: "multipart" })

_data := JSON.Load(data)

Clipboard := _data.imgurl

ToolTip, 图床上传完毕
return

 

 

将剪切板的图片保存到桌面

https://www.jianshu.com/p/ae048b5090f8

https://github.com/mmikeww/AHKv2-Gdip/blob/master/README.md

#Include src/Gdip.ahk 
createPic(PicPath)
{
    ; Start gdi+
    pToken := Gdip_Startup() 
    
        ;pBitmapAlpha := Gdip_CreateBitmapFromFile(PicPath)
        ;pBitmapAlpha := Gdip_BitmapFromScreen(0, "")
        ;pBitmapAlpha := Gdip_BitmapFromScreen(x "|" y "|" width "|" height)
        
        ;从剪切板直接获取位图
        pBitmapAlpha := Gdip_CreateBitmapFromClipboard()
        ;图片的宽度
        ImgWidth := Gdip_GetImageWidth(pBitmapAlpha)  
        ;图片的高度
        ImgHeight := Gdip_GetImageHeight(pBitmapAlpha)
        
        ;保存图片到指定的位置;第三个参数控制图片质量
        Gdip_SaveBitmapToFile(pBitmapAlpha, PicPath, "255")
        Gdip_DisposeImage(pBitmapAlpha)
    ; close gdi+    
    Gdip_Shutdown(pToken) 
    Traytip, 截图完毕:, 宽: %ImgWidth% 高: %ImgHeight%`n保存为: %PicPath%
}


!z::
; 先用QQ截图,然后再执行 !z,桌面就会有一张fuckyou.png
savePath := A_Desktop . "\fuckyou.png"
createPic(savePath)
return

 

 

 

hex 转换为 rgba

HexToRGB(color) {
    colorR := SubStr(color, 3, 2)
    colorG := SubStr(color, 5, 2)
    colorB := SubStr(color, 7, 2)
    colorR = 0x%colorR%
    colorG = 0x%colorG%
    colorB = 0x%colorB%
    SetFormat, IntegerFast, D
    colorR += 0
    SetFormat, IntegerFast, D
    colorG += 0
    SetFormat, IntegerFast, D
    colorB += 0
    colorRGB = rgba(%colorR%`, %colorG%`, %colorB%, 1)
    return colorRGB
}

!z::
    MouseGetPos, posX, posY
    PixelGetColor, color, %posX%, %posY%, Slow RGB
    Clipboard := HexToRGB(color)
return

 

通过sc码来设置热键

https://wyagd001.github.io/zh-cn/docs/KeyList.htm#SpecialKeys

!SC029::
Var =
(
``````javascript

``````
)
code(Var)
return

 

获取进程id,可以通过模糊title来查找。

WinGet, v, PID, , Chrome
Process, Close, % v        

 

动态添加热键

__TIP__(a = 123) {
    MsgBox, % a
}

!z::
    HFN := Func("__TIP__")
    Hotstring(":*:fuck", HFN.bind("321"))
return

 

 

GET请求,解决乱码问题

; 下载内容
ajax(url, q:=false, text:="正在为你下载代码,请保持网络顺畅")
{
    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    whr.Open("GET", url, true)
    whr.SetRequestHeader("Content-Type", "charset=GB2312")
    
    whr.Send()

    whr.WaitForResponse()
    
    if (q==false) {
        if (whr.ResponseText) {
            tip("下载成功")
        } else {
            tip("无内容返回")
        }
    }
    
    arr := whr.responseBody
    pData := NumGet(ComObjValue(arr) + 8 + A_PtrSize)
    length := arr.MaxIndex() + 1
    text := StrGet(pData, length, "utf-8")
    return text
    
    ; return  whr.ResponseText
}

 

AHK 解析JSON库

https://github.com/cocobelgica/AutoHotkey-JSON

#Include src/JSON.ahk              ; JSON Script

!z::
str =
(
{
    "a": 123
}
)

data := JSON.Load(str)

MsgBox, % data.a
return

 

注意索引是从1开始的。所以如果是数组,第一个的索引是1

!z::
json_str := ajax("https://gitee.com/api/v5/gists?access_token=6ab92e291bbe59b4301191b6aef2bc85&page=1&per_page=20")

data := JSON.Load(json_str)

MsgBox, % data[1].url
return

 

 

AHK 解析和使用JSON,依赖 ActiveScript.ahk

https://github.com/Lexikos/ActiveScript.ahk

#Include src/ActiveScript.ahk

jsonstr := "{a: 123}"

jsonParse =
(
eval('(' + jsonstr + ')')
)

script := new ActiveScript("JScript")
Result := script.Eval(jscontent)
MsgBox, % Result.a

 

 

AHK GUI 布局工具  SmartGUI Creator

https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm#Position

 

两个关于索引的重要认知:

1、SubStr 字符串截取,如果你想从后面开始取,那么索引应该设置为0,比如SubStr("123", 0, 1);

2、数组的第一位,是从1开始的。恶心吧?

 

获取按钮的状态

; 左键是否按紧了
KeyIsDown := GetKeyState("LButton")

KeyIsDown := GetKeyState("Alt")

KeyIsDown := GetKeyState("Ctrl")

 

powershell.exe 与 ahk结合

!z::
; zip名字
zipname := "vue3-template.zip"
; 文件夹名字
zippath := "./vue3-template"
; 下载文件的地址
url := "https://raw.githubusercontent.com/dragon8github/Pandora/master/template/vue3-template.zip"
; 由于要使用git命令,所以要将window格式转化为unix格式的路径
desk := StrReplace(A_Desktop, "\", "/")
; 文件夹的名字
name := desk . "/vue3_template_" . A_YYYY . A_MM . A_DD . A_Hour . A_Min . A_Sec
; 一系列命令 
command = 
(
mkdir %name% ; cd %name% ; Invoke-WebRequest -uri "%url%" -OutFile "%zipname%" ; Expand-Archive -Path %zipname% -DestinationPath . ; rm %zipname%
)
run, powershell.exe %command%
return

 

 

 

热字符串定义一个很重要的技巧:

::.f::
Var =
(
.forEach((val, key) => {})
)
code(Var)
return

::f::
Var =
(
function () {}
)
code(Var)
return

我定义了.f 和 f ,但如果我输出 a.f , 我期待触发 .f , 但实际上是除非 f

其实这样这样设置 .f即可。 :?:.f::

:?:.f:: 
Var =
(
.forEach((val, key) => {})
)
code(Var)
return

 

 

关闭进程,其实特别实用

https://wyagd001.github.io/zh-cn/docs/commands/Process.htm#ex1

Run notepad.exe,,, NewPID
Process, Priority, %NewPID%, High
MsgBox The newly launched Notepad's PID is %NewPID%.

 

 全局变量global,居然只能这样使用?

txtit() {
  ; 全局变量真的只能这样用了,定义在外面没有办法生存。
  global pidary := pidary ? pidary : []
  
  pidary.push("110")

  return
}

!x::
txtit()
txtit()
txtit()
MsgBox, % pidary.Length()
return

 

 

 

强大的 Spy 探测检测窗口的信息。

只需要右键小图标,选中 spy window 即可,最好选中右上角的 Follow Mouse 方便选中。我们来实战一下如何查看搜狗输入法的窗口

我们得知输入法的窗口信息为: ‘ahk_class SoPY_Comp’。这样我就能搞很多事情了。

    if (WinExist("ahk_class SoPY_Comp")) {
          MsgBox, 123
    }

后记:win10的输入法有问题,就算能获取,Send的时候也很多问题。最大的问题在于哪怕出现输入法了,还是会在UI中输出英文,最好的办法还是使用搜狗等第三方吧。

建议屏蔽win10输入法:https://jingyan.baidu.com/article/ed2a5d1f99277909f7be1753.html

 

 

 

  Run,% "C:\Windows\notepad.exe",,, pid
  WinWait, ahk_pid %pid%
  WinMove, ahk_pid %pid%,,  0, 0, (A_ScreenWidth)/3, (A_ScreenHeight)
  Return

 

 

listview 点击事件(click,rightclick)

必须设置AltSubmit参数才行。

Gui, ISearch:Add, ListView, r7 w800 h600 gMyListView AltSubmit xs yp+40, Name|Path


MyListView:
if (A_GuiEvent = "Normal") {
  MsgBox, %A_EventInfo%
}

if (A_GuiEvent = "RightClick") {
  MsgBox, %A_EventInfo%
}
return

 

 

 

GUI的关闭事件

GuiEscape:
GuiClose:
    Gui, Hide
return

PandoraGuiEscape:
PandoraGuiClose:
    Gui, Pandora:Hide
return

 

获取GUI Edit的值。

(PS: Pandora:  是我的GUI 的ID,如果没有可以省略。

GuiControlGet, OutputVar, Pandora:, SearchContent, Text

 

数组简单循环

myarray := ["a", "b", "c", "d"]
For key, value in myarray
            MsgBox %key% = %value%

 

gui Listview 组件的使用

https://wyagd001.github.io/zh-cn/docs/commands/ListView.htm#Intro

PS: 主要是我的GUI叫 Pandora 才需要加入 Pandora: ,否则移出

; 创建含名称和大小两列的 ListView:
Gui, Pandora:Add, ListView, r7 w260 gMyListView xs, Name|Path

Gui, Pandora:Default

; 从文件夹中获取文件名列表并把它们放入 ListView:
Loop, %A_MyDocuments%\*.*
    LV_Add("", A_LoopFileName, A_LoopFileSizeKB)

LV_ModifyCol()  ; 根据内容自动调整每列的大小.
LV_ModifyCol(2, "Integer")  ; 为了进行排序, 指出列 2 是整数.

 

SendLevel 控制热键和热字串是否忽略模拟的键盘和鼠标事件.

SendLevel 1
Send, canvas.game{tab}

 

GuiControlGet 如果有GUI,那么需要这样用,譬如我的GUI是Pandora

GuiControlGet, OutputVar, Pandora:, ClipHistory, Text

 

获取当前是否为中文输入法

!x::
CoordMode Pixel
ImageSearch, FoundX, FoundY, 0, 0, A_ScreenWidth, A_ScreenHeight, *25 static/icon/cn.png
ImageSearch, FoundX2, FoundY2, 0, 0, A_ScreenWidth, A_ScreenHeight, *25 static/icon/cn2.png
if (FoundX != "" || FoundX2 != "") {
    MsgBox, 目前是中文输入法
}
return

 

标题和聚焦相关

# 获取当前活跃窗口标题
WinGetTitle, title, A

# 根据title获取当前的ahk_class
WinGetClass, outval, 标题名

# 获取当前活跃窗口ahk_class
WinGetClass, outval, A

 

 无限循环和停止。

ISSTOP := false

F5::
Loop {
    Click
    Sleep, 10
    
    if (ISSTOP) {
        break
    }
}
    
return

F6::
ISSTOP := true
return

 

 

用IE打开网站示例

run, iexplore.exe http://120.196.128.45:801/
ExitApp 


官方有批量定义快捷键的方法,但却没有批量定义热字符串的办法,文档又非常不友好,只能艰难的摸索出来。
- 替换热字符串
- 替换label
- 替换函数方法

 

// 1、替换热字符串
Loop, 1000 {
Hotstring("::h" . A_Index, "height: " . A_Index . "px;") 
}

// 2、替换为label
Loop, 1000 {
Hotstring(":X:h" . A_Index, "HEIGHT_HANDLE_LABEL")
}

HEIGHT_HANDLE_LABEL() {
MsgBox, % A_ThisHotkey
}

// 3、替换函数方法
HEIGHT_HANDLE_LABEL() {
MsgBox, % A_ThisHotkey
}

Loop, 1000 {
HFN := Func("HEIGHT_HANDLE_LABEL")
Hotstring(":X:h" . A_Index, HFN)
}

 

 

 

 

如何输出双引号? 其实就是两个双引号即可

Var := "我的名字是 "" Lee "" "
MsgBox, % Var

 

正则表达式获取子匹配,请注意下面的 OutputVar4 变量

强烈推荐看看:https://autohotkey.com/boards/viewtopic.php?f=27&t=7888&hilit=%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F

Var := "<div class = 'departmental'>"
RegExMatch(Var, "im)class(\s*)=(\s*)('|""){1}(.+?)('|""){1}", OutputVar)
MsgBox, % OutputVar  ; class = 'departmental'
MsgBox, % OutputVar4 ; departmental

 

 

换行符和循环输出数组Array

https://wyagd001.github.io/zh-cn/docs/Objects.htm#Usage_Simple_Arrays

https://wyagd001.github.io/zh-cn/docs/misc/Arrays.htm

^!r::
    tmp := Clipboard
    if (StrLen(tmp)) {
        array := StrSplit(tmp, "`n")
        For key, value in array
            MsgBox %key% = %value%
    }
return

 

 

执行已定义好的热字符串,Gosub 或者 Goto

https://wyagd001.github.io/zh-cn/docs/Hotstrings.htm

::ff::
  MsgBox, 123
return

::test::
 Gosub ::ff
return

 

 

发送纯文本,这对代码很友好,而且不受输入法的影响,缺点是一旦使用{text},就无法使用#!+这些了

https://wyagd001.github.io/zh-cn/docs/commands/Send.htm#blind

Send, {text} console.log('')
Send, {left 2}

 

 

ahk调用cmd示例(暂时不知道如何调用bash)

https://wyagd001.github.io/zh-cn/docs/commands/Run.htm

RunWaitOne(command) {
    ; WshShell 对象: http://msdn.microsoft.com/en-us/library/aew9yb99
    shell := ComObjCreate("WScript.Shell")
    ; 通过 cmd.exe 执行单条命令
    exec := shell.Exec(ComSpec " /C " command)
    ; 读取并返回命令的输出
    return exec.StdOut.ReadAll()
}

a := RunWaitOne("node -v")
MsgBox, % a

 

 

GUI Submit, NoHide 的作用

https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm#ex2

Gui, Add, Text,, First name:
Gui, Add, Text,, Last name:
Gui, Add, Edit, vFirstName ym  ; ym 选项开始一个新的控件列.
Gui, Add, Edit, vLastName
Gui, Add, Button, default, OK  ; ButtonOK(如果存在)会在此按钮被按下时运行.
Gui, Show,, Simple Input Example
return  ; 自动运行段结束. 在用户进行操作前脚本会一直保持空闲状态.

GuiClose:
ButtonOK:
Gui, Submit, NoHide   ; 保存用户的输入到每个控件的关联变量中.
MsgBox You entered "%FirstName% %LastName%".
ExitApp

 

 

 GUI 的BUTTON的事件绑定

Gui, Add, Button, w740 h30 Default, FUCK

ButtonFUCK:
    ; 保存用户的输入到每个控件的关联变量中.
    Gui, Submit, NoHide 
    MsgBox, 123
return

 

 

AHK GUI 布局重点教程

核心API:

  • ys:新列
  • xs:新行,通常结合sction一起使用
  • section:形成一个新的块,通常结合xs一起使用

 

Gui, Add, Text, gAllSearchA W120 yp+10, 搜索引擎类:
Gui, Add, Checkbox, gMySubroutine Checked HwndMyEditHwnd vbd, 百度
Gui, Add, Checkbox, vgoogle, Google
Gui, Add, Checkbox, vgithub, Github
Gui, Add, Checkbox, vso, Stack Overflow
Gui, Add, Checkbox, vsegmentfault, SegmentFault
Gui, Add, Checkbox, vcylee, 博客园

Gui, Add, Text, gAllSearchB W120 ys, 翻译类:
Gui, Add, Checkbox, vbdfy, 百度翻译   
Gui, Add, Checkbox, vyoudaofy, 有道翻译
Gui, Add, Checkbox, vgooglefanyi, Google翻译

Gui, Add, Text, gAllSearchC W120 ys, 音乐类:
Gui, Add, Checkbox, vwy, 网易云音乐   
Gui, Add, Checkbox, vqq, QQ音乐
Gui, Add, Checkbox, vdog, 酷狗音乐
Gui, Add, Checkbox, vxiami, 虾米音乐

Gui, Add, Text, gAllSearchD W120 ys, 社区类:
Gui, Add, Checkbox, vjuejin, 掘金
Gui, Add, Checkbox, vjianshu, 简书
Gui, Add, Checkbox, vcsdn, CSDN
Gui, Add, Checkbox, vzhihu, 知乎

Gui, Add, Text, gAllSearchE W120 ys, 购物类:
Gui, Add, Checkbox, vtaobao, 淘宝
Gui, Add, Checkbox, vjingdong, 京东
Gui, Add, Checkbox, vdangdang, 当当
Gui, Add, Checkbox, vamazon, 亚马逊
Gui, Add, Checkbox, vsuning, 苏宁易购

Gui, Add, Text,  W120 Section xs yp+50, 常用导航:
Gui, Add, Link,, <a href="https://github.com">github</a>
Gui, Add, Link,, <a href="https://legacy.gitbook.com">gitbook</a>
Gui, Add, Link,, <a href="https://www.cnblogs.com/cylee">博客园</a>

Gui, Add, Text,  W120 ys, 其他:
Gui, Add, Link,, <a href="http://youmightnotneedjquery.com/">notjQuery</a>
Gui, Add, Link,, <a href="chrome://inspect/#devices">安卓调试</a>
Gui, Add, Link,, <a href="https://wyagd001.github.io/zh-cn/docs/Tutorial.htm">AHK官网</a>

Gui, Add, Text,  W120 ys, 娱乐:
Gui, Add, Link,, <a href="https://www.bilibili.com/">哔哩哔哩</a>
Gui, Add, Link,, <a href="http://www.dilidili.wang/">嘀哩嘀哩</a>
Gui, Add, Link,, <a href="http://i.youku.com/u/UNTUzOTAwMzQ0">Ted魔兽</a>
Gui, Add, Link,, <a href="http://e.xitu.io/">掘金前端</a>

Gui, Add, Text,  W120 ys, 代理:
Gui, Add, Link,, <a href="http://www.xicidaili.com/nn">西刺</a>
Gui, Add, Link,, <a href="https://proxy.l337.tech/txt">l337</a>
Gui, Add, Link,, <a href="http://www.66ip.cn/nm.html">66ip</a>

Gui, Add, Text, W120 ys, 站长工具:
Gui, Add, Link,, <a href="http://tool.oschina.net/codeformat/html">代码格式化</a>
Gui, Add, Link,, <a href="https://tool.lu/html/">代码美化</a>
Gui, Add, Link,, <a href="http://jsbeautifier.org/">jsbeautifier</a>
Gui, Add, Link,, <a href="http://tool.chinaz.com/Tools/urlencode.aspx">Urlencode/Unicode</a>

Gui, Add, Text,  W120 Section xs yp+40, layer/layui:
Gui, Add, Link,, <a href="http://layer.layui.com/">layer</a>
Gui, Add, Link,, <a href="http://www.layui.com/doc/">layui文档</a>
Gui, Add, Link,, <a href="http://www.layui.com/demo/">layer示例</a>
Gui, Add, Link,, <a href="https://github.com/sentsin/layui/">layui-github</a>

Gui, Add, Text,  W120 ys, Vue:
Gui, Add, Link,, <a href="http://vuejs.org/">vue</a>
Gui, Add, Link,, <a href="http://vuex.vuejs.org">vuex</a>
Gui, Add, Link,, <a href="http://router.vuejs.org ">vue-router</a>
Gui, Add, Link,, <a href="https://github.com/opendigg/awesome-github-vue">vue-awesome</a>

Gui, Add, Text,  W120 ys, ElementUI:
Gui, Add, Link,, <a href="http://element-cn.eleme.io/#/zh-CN/component/radio">ElementUI</a>
Gui, Add, Link,, <a href="https://github.com/ElemeFE/element/blob/dev/packages/">Element-github</a>

Gui, Add, Text, W120 ys, mint-ui:
Gui, Add, Link,, <a href="http://elemefe.github.io/mint-ui/#/">mint-ui</a>
Gui, Add, Link,, <a href="http://mint-ui.github.io/docs/#/">mint-ui-github</a>

Gui, Add, Text,  W120 ys, 最近浏览:
Gui, Add, Link,, <a href="http://guss.one/guss/register.html?code=ec19c0ca">guss</a>
Gui, Add, Link,, <a href="http://www.51ym.me/User/Default.aspx">易码</a>
Gui, Add, Link,, <a href="http://www.manbiwang.com/#/">满币网</a>

 

 

获取控件GUI控件的对象

再进一步根据API操作就简单了

Gui, Add, Checkbox, vsuning, 苏宁易购

; 设置为选中 GuiControl,, suning,
1

 

 

设置GUI控件的事件

Gui, Add, Text, gAllSearchD W120 ym, 社区类:

AllSearchD:
    MsgBox, 123return

 

 

(hack) 在ahk中使用JavaScript

https://autohotkey.com/boards/viewtopic.php?f=6&t=4555

https://github.com/Lexikos/ActiveScript.ahk

#Include <ActiveScript>

script := new ActiveScript("JScript")
Result := script.Eval("parseInt(Math.random() * 10 + 1)")
MsgBox, % Result

 

 

最大化当前窗口和还原当前窗口

!enter::
    WinGet, OutputVar, MinMax, A
    if (OutputVar == 1) {
        WinRestore, A
    } else {
        WinMaximize, A
    }
return

 

 

 

获取当前桌面路径:MsgBox, %A_Desktop%

 

GUI的语法

官方demo:https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm#Examples

官方文档:https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm

控件列表:https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm#Add

详细demo:https://www.cnblogs.com/CyLee/p/9198059.html

Gui, Add, Text, W120, 搜索引擎类:
Gui, Add, Checkbox, gMySubroutine vbd Checked HwndMyEditHwnd, 百度
Gui, Add, Checkbox, vgoogle, Google
Gui, Add, Checkbox, vgithub, Github
Gui, Add, Checkbox, vso, Stack Overflow

Gui, Add, Text, W120 ym, 翻译类:
Gui, Add, Checkbox, vbdfy, 百度翻译   
Gui, Add, Checkbox, vyoudaofy, 有道翻译
Gui, Add, Checkbox, vgooglefanyi, Google翻译

Gui, Add, Text, W120 ym, 音乐类:
Gui, Add, Checkbox, vwy, 网易云音乐   
Gui, Add, Checkbox, vqq, QQ音乐
Gui, Add, Checkbox, vdog, 酷狗音乐
Gui, Add, Checkbox, vxiami, 虾米音乐

Gui, Add, Text, W120 ym, 社区类:
Gui, Add, Checkbox, vjuejin, 掘金
Gui, Add, Checkbox, vjianshu, 简书
Gui, Add, Checkbox, vcsdn, CSDN
Gui, Add, Checkbox, vzhihu, 知乎
Gui, Add, Checkbox, vsegmentfault, SegmentFault

; ym 可以 y轴换列,有点类似float:left ,而 xm可以换行,有点类似clear:both
Gui, Add, Edit, r9 vFirstName w300 Limit50 ym , 请输入你要搜索的内容
Gui, Color, E6FFE6
Gui, Margin, 10, 10
Gui, Add, Button, w300 h30, OK
Gui, Show,, Simple Input Example
return 

; +g 其实就是添加吧
MySubroutine:
    MsgBox, %MyEditHwnd%
    MsgBox, %A_EventInfo%, %A_GuiEvent%, %A_GuiControl%, %A_Gui%
return


GuiClose:
ButtonOK:
Gui, Submit  ; 保存用户的输入到每个控件的关联变量中.
    if (bd == 1) {
    }
return

 

 

 

 

 

自定义托盘到图标

 

 

文本插入

~^c::
    Clipboard := 
    Send, ^c
    ClipWait
    time := A_YYYY . "/" . A_MM . "/" . A_DD . " " . A_Hour . ":" . A_Min . ":" . A_Sec
    FileAppend, __________________%time%__________________`n`n%Clipboard%`n`n, ./tmp.txt
return

 

字符串操作:去掉空白、去掉换行、获取长度

if (StrLen(Trim(StrReplace(Clipboard, "`r`n"))) != 0) {}

 

快速搜索demo

!space::
    InputBox, OutputVar, title, what's your Q?
    if (ErrorLevel == 0)
    {
        /*
        RUN, https://www.zhihu.com/search?type=content&q=%OutputVar%
        RUN, https://segmentfault.com/search?q=%OutputVar%
        RUN, https://www.google.com/search?q=%OutputVar%
        RUN, https://stackoverflow.com/search?q=%OutputVar%
        */
        RUN, https://www.baidu.com/s?wd=%OutputVar%
    }
Return

 

 快速搜索音乐demo

; 快速搜索音乐
!m::
    InputBox, OutputVar, title, enter a music name?
    if (OutputVar != "") 
    {
        RUN, http://music.163.com/#/search/m/?s=%OutputVar%
        RUN, https://y.qq.com/portal/search.html#w=%OutputVar%
        RUN, https://www.xiami.com/search?key=%OutputVar%
        RUN, http://www.kugou.com/yy/html/search.html#searchType=song&searchKeyWord=%OutputVar%
    }
return

 

 

(重要) 使用 #include 引入其他代码段

 https://wyagd001.github.io/zh-cn/docs/commands/_Include.htm

; 这里是htinfo.ahk
::test::
    MsgBox, 321
return


; 这里是main.ahk
#include htinfo.ahk

 

热键也支持up 和 down到定义

F6 Up::
    MsgBox, 123
return

 

 

(重要)定义多个热键同个功能

 

修改托盘图标,但不能修改编译好的图标,其实没什么意思

Menu, Tray, Icon, ../static/favicon-201806020842523.ico

 

 

(重要)其实不需要输入到文本,也可以触发的。譬如

::layui::
    run, https://github.com/dragon8github/ahk/blob/master/template/layui_template.zip?raw=true
return

我们只需要输入layui 然后按下回车即可,不一定需要输出到面板。

 

scite4ahk 编辑器中间的神奇运用:鼠标中键列出所有的快捷键和定义。包含#include的东西

 

 

-12、字符串累加,时间输出

>^t::
time := A_YYYY . "/" . A_MM . "/" . A_DD . " " . A_Hour . ":" . A_Min . ":" . A_Sec
Send, % time
return

 

 

-11、确认框

MsgBox, 4,, Would you like to continue? (press Yes or No)
IfMsgBox Yes
    MsgBox You pressed Yes.
else
    MsgBox You pressed No.

 

-10、十分常用的功能,获取当前定义的快捷键A_ThisHotkey

::posa::
    SendInput, 
(
position: absolute`;
)
MsgBox, % A_ThisHotkey
Return

 

 

-9、叠加剪切板

::Test::
clipboard =   

Var = 
(
--Start Script
sendToAHK = function (key)
      --print('It was assigned string:    ' .. key)
      local file = io.open("C:\\Users\\TaranWORK\\Documents\\GitHub\\2nd-keyboard-master\\LUAMACROS\\keypressed.txt", "w") -- writing this string to a text file on disk is probably NOT the best method. Feel free to program something better!
      --Make sure to substitute the path that leads to your own "keypressed.txt" file, using the double backslashes.
      --print("we are inside the text file")
      file:write(key)
      file:flush() --"flush" means "save"
      file:close()
      lmc_send_keys('{F24}')  -- This presses F24. Using the F24 key to trigger AutoHotKey is probably NOT the best method. Feel free to program something better!
end 
)
RegExMatch(Var, "i)(\b\w+\b)(?CCallout)") 

Callout(m) {
    clipboard .= m . ","
   ; __Var__ = %__Var__% . %m%
    ;__Array__.Insert(m)
    ;MsgBox, % __Var__
    ;MsgBox m=%m% `n m1=%m1% `n m2=%m2% 
   ; __Var__ .= m
    return 1
}
return

 

 

-8、排序

MyVar = 5,3,7,9,1,1,13,999,-4
Sort MyVar, U N D,  ; N数值排序, D默认使用逗号作为分隔符, U移除重复项
MsgBox %MyVar%   ; 结果是 -4,1,3,5,7,9,13,999*/
Return

 

 

 

-7、累加字符串,和php一样, .= 即可

Array := []
Array.Insert("d")
Array.Insert("a")
Array.Insert("b")
Array.Insert("c")

for index, element in Array ; 在大多数情况下建议使用枚举的方式.
{
    ; 使用 "Loop", 索引必须是连续的数字, 从 1 到
    ; 数组中元素的个数 (或者必须在循环中进行计算).
    ; MsgBox % "Element number " . A_Index . " is " . Array[A_Index]

    ; 使用"for",同时提供了索引(或"")及与它关联
    ; 的值,并且索引可以是您选择的*任何*值.
    ;MsgBox % "Element number " . index . " is " . element
    Var .= element
    MsgBox, % Var
}

 

 

-6、数组的创建和遍历

请注意,数组不能直接msg出来,只能通过for遍历

::arr::
    Array := []
    Array.Insert("a")
    Array.Insert("b")
    Array.Insert("c")
    Array.Insert("d")
    
    for index, element in Array ; 在大多数情况下建议使用枚举的方式.
    {
        ; 使用 "Loop", 索引必须是连续的数字, 从 1 到
        ; 数组中元素的个数 (或者必须在循环中进行计算).
        ; MsgBox % "Element number " . A_Index . " is " . Array[A_Index]

        ; 使用"for",同时提供了索引(或"")及与它关联
        ; 的值,并且索引可以是您选择的*任何*值.
        MsgBox % "Element number " . index . " is " . element
    }

Return

 

 

 

-5、打开文本,等待文本,聚焦文本

+d::
    InputBox, OutputVar, title, enter your download url?
    if (OutputVar != "") {
        text := ajax(OutputVar)
        RUN, notepad
        WinWaitActive, 无标题 - 记事本, , 2
        if ErrorLevel {
            MsgBox, WinWait timed out.
        }
        else {
            ; 这里需要聚焦一下
            Winactivate
            code(text)
        }
    }
return

 

 

-4、正则匹配,这里最难和最坑的其实就是对\b的理解

https://wyagd001.github.io/zh-cn/docs/misc/RegExCallout.htm

::Test::
Var = 
(
--Start Script
sendToAHK = function (key)
      --print('It was assigned string:    ' .. key)
      local file = io.open("C:\\Users\\TaranWORK\\Documents\\GitHub\\2nd-keyboard-master\\LUAMACROS\\keypressed.txt", "w") -- writing this string to a text file on disk is probably NOT the best method. Feel free to program something better!
      --Make sure to substitute the path that leads to your own "keypressed.txt" file, using the double backslashes.
      --print("we are inside the text file")
      file:write(key)
      file:flush() --"flush" means "save"
      file:close()
      lmc_send_keys('{F24}')  -- This presses F24. Using the F24 key to trigger AutoHotKey is probably NOT the best method. Feel free to program something better!
end 
)
   ;  FoundPos := RegExMatch(Var, "iO)\s(\w+)|(\w+)\s", SubPat)
    ; MsgBox, % Match
    
    ; 保证特征只有一个。那么空格是很好的
    
;Haystack = The quick brown fox jumps over the lazy dog.
;RegExMatch(Haystack, "i)(\b\w+\b)(?CCallout)")

RegExMatch(Var, "i)(\b\w+\b)(?CCallout)") 

Callout(m) {
    MsgBox m=%m% `n m1=%m1% `n m2=%m2% 
    return 1
}
return

 

 

-3、GUI

https://wyagd001.github.io/zh-cn/docs/commands/Gui.htm

!q::
    Var = 
    (
        审查清单
        1、确定设计稿的开发友好性(开发成本、无法完美还原效果图的地方)
        2、确定一些特殊的元素是否有合理的边界处理(如文案超出外层容器的情况)        
        3、确定页面的框架结构(Layout)        
        4、确定跨页面可复用组件(Site Global Component)        
        5、确定当前页面可复用组件(Page Component)        
        ...
        
        把页面想象成一套房子
        - HTML:可以决定网页架构结构(房子有几间房,各个区域的用途是什么)
        - Css:可以决定网页的样式和布局(房间的颜色,布局,大小,装修,主题,色调)
        - JS:决定页面具体交互和功能(智能家居,如空调根据温度自动启动和调节温度,灯光自动调节色温,房门感应自动打开和关闭)
    )
    Gui, font, s14, Microsoft yahei
    Gui, color, f2f2f2
    Gui, Add, Text,, %Var%
    Gui, Show, W800 H600 X0 Y0 Center AutoSize, 标题
    return
Return

 

 

-2、Send打断文本的解决方案,利用剪切板和复制黏贴

c(code)
{
tmp := Clipboard
Clipboard := code
SendInput, ^V
Clipboard := tmp
}

::gettop::
Var = 
(
function getElementTop(element){
    try {
      var actualTop = element.offsetTop;
      var current = element.offsetParent;
      while (current !== null){
        actualTop += current.offsetTop;
        current = current.offsetParent;
      }
      return actualTop;
    } catch (e) {}
}
)
c(Var)
Return

 

-1、网络下载内容

https://segmentfault.com/a/1190000005041741

::gettop::
    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    ; Open() 的第三个参数代表同步或者异步,现在不用过多关注,true 就可以了
    whr.Open("GET", "https://autohotkey.com/download/1.1/version.txt", true)
    whr.Send()
    whr.WaitForResponse()
    version := whr.ResponseText
    MsgBox, % version
Return

 

::gettop::
    whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
    ; Open() 的第三个参数代表同步或者异步,现在不用过多关注,true 就可以了
    whr.Open("GET", "https://raw.githubusercontent.com/dragon8github/ahk/master/functions/gettop.js", true)
    whr.Send()
    TrayTip, 请稍后, 正在为你下载gettop代码,请保持网络顺畅, 20, 17
    whr.WaitForResponse()
    tmp := Clipboard
    Clipboard := whr.ResponseText
    send, ^V
    Clipboard := tmp
    TrayTip, 下载成功, (づ ̄3 ̄)づ╭❤~ , 20, 17
Return

 

 

 

 

1、官方示例

#z::Run https://autohotkey.com

^!n::if WinExist("Untitled - Notepad")
    WinActivate
else
    Run Notepad
return

 

1.0 、设置终止符(重要)

https://wyagd001.github.io/zh-cn/docs/Hotstrings.htm#EndChars

Hotstring("EndChars", "`n`t ")  ; 设置为回车键、tab键和空格键

默认是这个:
Hotstring("EndChars", "-()[]{}:;")

 

1.1.1 将中文符号强制转换为英文

; 无视输入法状态发送字符串uStr函数
uStr(str)
{
    charList:=StrSplit(str)
    SetFormat, integer, hex
        for key,val in charList
        out.="{U+ " . ord(val) . "}"
    return out
}

,::SendInput % uStr(",")​
?::SendInput % uStr("?")​
.::SendInput % uStr(".")​
!::SendInput % uStr("!")
{::SendInput % uStr("{")
}::SendInput % uStr("}")
[::SendInput % uStr("[")
]::SendInput % uStr("]")
`;::SendInput % uStr(";")
>+;::SendInput % uStr(":")
(::SendInput % uStr("(")
)::SendInput % uStr(")")
>+'::
    a = "
    SendInput % uStr(a)
Return
'::
    a = '
    SendInput % uStr(a)
Return

 

 

 

 

 

1.1、快速重启脚本

!r::
   send, ^s reload Return

 

1.2、使用常量,获取年月日

!d::
    Send, %A_YYYY%/%A_MM%/%A_DD%
Return

 

 1.3、赋值剪切板

!x::
    a = fuck you!!!!!!
    Clipboard = %a%
Return

 

 

2、快捷输入

^j::
    Send, My First Script
Return

 

2.1、明白 Send,和 SendInput的区别。前者是慢慢输入,后者是直接输入

::dg::
    Send, document.getElementById('')`;{left 3}
Return

::dg::
    SendInput, document.getElementById('')`;{left 3}
Return

 

3、补全

::ftw::Free the whales

输入 ftw 然后按下【空格、tab、回车、分号,感叹号等许多键时,会自动补全Free the whales】

 

4、弹出层

esc::
    MsgBox Escape!!!!
Return

 

5、弹出层2

::btw::
    MsgBox You typed "btw".
Return

 

 6、连续

^j::
    MsgBox Wow!
    MsgBox this is
    Run, Notepad.exe
#IfWinActive 无标题 - 记事本
WinWaitActive, 无标题 - 记事本 Send,
7 lines{!}{enter} SendInput, inside the ctrl{+}j hotkey Return

 亮点在于 #IfWinActive 无标题 - 记事本 和  WinWaitActive, 无标题 - 记事本。

前者是判断当前是否为记事本,后者是等待

 

7、组合键

Numpad0 & Numpad1::
    MsgBox You pressed Numpad1 while holding down Numpad0.
Return

Numpad0 & Numpad2::
    Run Notepad
Return

同时按下0+1或者0+2试试,就像按Ctrl + C 一样即可,但必须是右侧九宫格

 

 8、案例3的加强版,自动补全不需要其他按键

:*:ftw::Free the whales

输入 ftw就自动变成Free the whales

 

9、监听当前窗口,其实案例6就已经展示了。这里再补习一下

#IfWinActive 无标题 - 记事本
#space::
    MsgBox You pressed Win+Spacebar in Notepad.
Return

新开一个nodepad,然后按下快捷键即可。非常实用

 

10、如何添加注释

; 这是注释
#IfWinActive 无标题 - 记事本!q::
    MsgBox, You pressed Alt and Q in Notepad.
Return
#IfWinActive

 

 11、#IfWinActive作用域、代码块 下才有效

; Notepad
#IfWinActive ahk_class Notepad
#space::
    MsgBox, You pressed Win+Spacebar in Notepad.
Return
::msg::You typed msg in Notepad
#IfWinActive

 只有在Nodepad下输入msg + 【enter、space...等键】才有效果

 

12、输入 j 补全

~j::
    Send, ack
Return

 

 13、多个监听

#i::
    Run, http://www.baidu.com/
Return

^p::
    Run, notepad.exe
Return

~j::
    Send, ack
Return

:*:acheiv::achiev
::achievment::achievement
::acquaintence::acquaintance
:*:adquir::acquir
::aquisition::acquisition
:*:agravat::aggravat
:*:allign::align
::ameria::America

 

 14、组合键

^b::                                      
    Send, {ctrl down}c{ctrl up}               ; 等于按下Ctrl + C ,然后松开Ctrl键 
    SendInput, [b]{ctrl down}v{ctrl up}[/b]   ; 输入[b]然后按下Ctrl + V,松开Ctrl键,然后输入[/b]
Return     

正式开发不可能那么复杂,而是使用热键,譬如

^b::                                      
    Send, ^c               ; 等于按下Ctrl + C ,然后松开Ctrl键 
    SendInput, [b]^v[/b]   ; 输入[b]然后按下Ctrl + V,松开Ctrl键,然后输入[/b]
Return     

 

 15、send换行快速使用enter

>^i::                                      
Send,
(
Line 1
Line 2
Apples are a fruit.
)

 

 16、函数的使用

Add(x, y)
{
    return x + y  
}

^j::
    Send, % Add(2, 3)
Return

 

17、函数直接Send,表达式,记得要加%

Add(x, y)
{
    Send, % x + y
}

^j::
    Add(2, 3)
Return

 

 18、函数,拼接字符串

Add(x)
{
    return "{{}" x "{}}"
}

^j::
    Send, % Add("//...")
Return

 

19、新建菜单,大有作为的工具

更多实例请参考:https://wyagd001.github.io/zh-cn/docs/commands/Menu.htm

我的做法和官方的做法不一样,而且也不符合复用和缓存的理念。但却非常实用,更关键的是能用!如果按照官方的做法是有问题的。在正式实战的时候

menu,add 默认会去掉重复项,但却不会去掉分隔符,也就是空值,所以为了方便直接每次显示完后删除所有最好了。

!p::
    ; Create the popup menu by adding some items to it.
    Menu, PythonMenu, Add, Item1, PythonHandler
    Menu, PythonMenu, Add, Item2, PythonHandler
    Menu, PythonMenu, Add  ; Add a separator line.

    ; Create another menu destined to become a submenu of the above menu.
    Menu, Submenu1, Add, Item1, PythonHandler
    Menu, Submenu1, Add, Item2, PythonHandler

    ; Create a submenu in the first menu (a right-arrow indicator). When the user selects it, the second menu is displayed.
    Menu, PythonMenu, Add, My Submenu, :Submenu1

    Menu, PythonMenu, Add  ; Add a separator line below the submenu.
    Menu, PythonMenu, Add, Item3, MenuHandler  ; Add another menu item beneath the submenu.
    Menu, PythonMenu, Show  ; i.e. press the Win-Z hotkey to show the menu.
    Menu, PythonMenu, DeleteAll
return

PythonHandler:
    MsgBox You selected %A_ThisMenuItem% from the menu %A_ThisMenu%.
return

 

 

20、弹窗获取用户输入

https://wyagd001.github.io/zh-cn/docs/commands/InputBox.htm

#space::
InputBox, OutputVar, title, enter a music name?
if (OutputVar!="")
   MsgBox, That's an awesome name, %OutputVar%.

 也可以用 ErrorLevel 来区分用户点击的是确认还是取消

InputBox, UserInput, Phone Number, Please enter a phone number., , 640, 480
if ErrorLevel
    MsgBox, CANCEL was pressed.
else
    MsgBox, You entered "%UserInput%"

 

21、获取鼠标位置的颜色

!a::  ; Control+Alt+Z hotkey.
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%
Clipboard = %color%
return

 

22、弹出气泡提示TrayTip

https://wyagd001.github.io/zh-cn/docs/commands/TrayTip.htm

!a::
MouseGetPos, MouseX, MouseY
PixelGetColor, color, %MouseX%, %MouseY%
Clipboard = %color%
TrayTip, my title, current color is `n %color%, 20, 17
return

 

23 关闭输入法

SwitchIME(dwLayout){
    HKL:=DllCall("LoadKeyboardLayout", Str, dwLayout, UInt, 1)
    ControlGetFocus,ctl,A
    SendMessage,0x50,0,HKL,%ctl%,A
}

esc::
    ; 下方代码可只保留一个
    SwitchIME(0x08040804) ; 英语(美国) 美式键盘
    ;SwitchIME(0x04090409) ; 中文(中国) 简体中文-美式键盘
return
https://www.bilibili.com/video/av78639809/x::    Send, {LButton Down}    sleep, 1    Send, {LButton Up}return
 
posted @ 2018-04-19 08:54  贝尔塔猫  阅读(7137)  评论(0编辑  收藏  举报