AHK多个脚本共享全局变量
2021-07-31 18:45:44
;---------------------------
; AHK多个脚本共享全局变量 v1.0
;
; 作者:FeiYue
;
; 说明:这是简单的方法实现多脚本共享内存。
; 采用独立的全局变量管理进程,从而
; 使某个脚本重启或退出后不影响效果。
;---------------------------
#NoEnv
; 模仿第一个脚本,使用F1热键读取全局变量 a1
F1::
{
; 读取全局变量 a1 的值
a1:=Global_getvar("a1")
; 修改全局变量 a1 的值,使其值加1
a1++
Global_setvar("a1", a1)
; 在鼠标的右上边显示提示
MouseGetPos, x1, y1
ToolTip, 第一个脚本显示全局变量 a1=%a1%, x1+20, y1-20, 1
}
; 用定时器代替无限循环,从而两个热键可以同时运行
SetTimer,, 100
return
; 模仿第二个脚本,使用F2热键读取全局变量 a1
F2::
{
; 读取全局变量 a1 的值
a2:=Global_getvar("a1")
; 在鼠标的右下边显示提示
MouseGetPos, x2, y2
ToolTip, 第二个脚本显示全局变量 a1=%a2%, x2+20, y2+20, 2
}
; 用定时器代替无限循环,从而两个热键可以同时运行
SetTimer,, 100
return
; 按Esc热键退出程序
Esc::ExitApp
;========== 下面是函数 ==========
; 获取全局变量的值
Global_getvar(var) {
if !(var~="^\S{1,253}$")
return
if Global_createvar(var)
ControlGetText, value
return, value
}
; 修改全局变量的值
Global_setvar(var, value="") {
if !(var~="^\S{1,253}$")
return
if Global_createvar(var)
ControlSetText,, %value%
}
; 根据变量名称生成全局变量
Global_createvar(var) {
DetectHiddenWindows, On
IfWinExist, [Global][%var%]
return, 1
global DebugTip:="正在生成全局变量:" var " ——"
; 先启动全局变量管理进程
IfWinNotExist, <<Global>>
{
s=
(%
#NoEnv
#NoTrayIcon
#SingleInstance force
Menu, Tray, Icon, Shell32.dll, 19
Menu, Tray, Tip, 全局变量管理进程
DetectHiddenWindows, On
IfWinExist, <<Global>>
ExitApp
Gui, Add, Edit, vMyEdit
Gui, Show, Hide, <<Global>>
index:=0
return
GuiClose:
GuiControlGet, var,, MyEdit
if (var!="")
{
GuiControl,, MyEdit
index++
Gui, var%index%:Add, Text, w100 h100
Gui, var%index%:Show, Hide, [Global][%var%]
}
return
)
Exec(s)
}
WinWait, <<Global>>,, 10
if !ErrorLevel
{
ControlSetText,, %var%
WinClose
WinWait, [Global][%var%],, 10
}
return, !ErrorLevel
}
; 动态运行AHK代码
Exec(s, Ahk="", arg="") {
s:=RegExReplace(s, "\R", "`r`n")
Ahk:=Ahk ? Ahk : A_AhkPath
IfNotExist, %Ahk%
{
MsgBox, 4096, 错误, 找不到AHK主程序:%AHK% !
return
}
Try {
exec:=ComObjCreate("WScript.Shell").Exec(Ahk . " /r * " . arg)
exec.StdIn.Write(s)
exec.StdIn.Close()
}
Catch {
s:="`r`nFileDelete, %A_ScriptFullPath%`r`n" . s
f:=A_Temp "\~test1.tmp"
FileDelete, %f%
FileAppend, %s%, %f%
Run, %Ahk% /r "%f%" %arg%
}
}
;========== 脚本结束 ==========
;