求问大神:如何让ahk脚本同时只运行一个实例

遇到了问题?请先进行搜索(中文和英文),然后在此提问

Moderators: arcticir, tmplinshi

ljbljb
Posts: 1
Joined: 01 Jun 2015, 09:51

求问大神:如何让ahk脚本同时只运行一个实例

01 Jun 2015, 10:12

用ahk编写了个小程序,用于合并wireshark文件,希望鼠标选中几个文件后,用右键菜单中的命令合并。
编译成MergeCap.exe后,第一次运行先将该exe写入注册表的右键菜单,例如:
[HKEY_CLASSES_ROOT\*\shell\MergeCap\command]
@="\"D:\\MergeCap\\MergeCap.exe\" \"1%\""


但是测试发现比如选中2个文件后,用右键菜单中的MergeCap合并时,MergeCap.exe会运行2次! 我实际上希望只运行一次,并且和选中的文件无关,有什么解决的办法?
因为对注册表操作不熟悉,希望ahk脚本能避免该脚本同时有两个运行,该如何实现?
---------------
附ahk代码,方法比较笨,见笑:
---------------
clipboard =
send, ^c
clipwait, 1

RegRead, RegMerge, HKEY_CLASSES_ROOT, *\shell\MergeCap\command


if ErrorLevel or (strlen(RegMerge) != strlen(A_ScriptFullPath) + 3)
{
Regcmd := RegExReplace(A_ScriptFullPath, "ahk$", "exe") ;变成exe文件后,用"exe 1%"的话后面的1%加不上,所以干脆不加%1了,多增加下面一步
Regcmd2 = %Regcmd% `%1
RegWrite, REG_SZ, HKEY_CLASSES_ROOT, *\shell\MergeCap\command, , %Regcmd2%
if ErrorLevel
MsgBox, 16, ERROR, Write registry failed!
else
MsgBox, 64, Init successfully, 请选中wireshark文件后,用右键菜单中的命令合并`n如果改变了程序存放目录,需双击运行一次完成初始化。
ExitApp
}

clipboard = %clipboard%

RegRead, Wireshark_dir, HKEY_LOCAL_MACHINE, SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Wireshark.exe, Path
if ErrorLevel
{
MsgBox, 64, Wireshark not installed?, Can not find Wireshark install path from "HKEY_LOCAL_MACHINE, SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Wireshark.exe"
ExitApp
}

firstFile := RegExReplace(clipboard, "\r\n(.*)", "", LineNum_1)

;MsgBox, LineNum_1= %LineNum_1%
if LineNum_1 < 1
{
MsgBox, 48, Note:, 请选中多个文件,用右键中的MergeCap命令合并!
ExitApp
}

;capDir := RegExReplace(firstFile, "\\(.*?$", "\", LineNum) 居然不行!
StringGetPos, index, firstFile, \, R

if index >= 0
{
capDir := SubStr(firstFile, 1, index+1)
}
else
{
MsgBox, error1
ExitApp
}

capName = mergeTime_%A_Hour%%A_Min%%A_Sec%.cap

merged_file = %capDir%%capName%

merge_files := RegExReplace(clipboard, "\r\n", """ """)

inputStr = mergecap.exe -w "%merged_file%" "%merge_files%" > "%A_ScriptDir%\mergecap.txt" 2>&1

;Run, %comspec% /k "mergecap.exe -w "%merged_file%" "%merge_files%"" ;not working
RunWait, %comspec% /c %inputStr%, %Wireshark_dir%, Hide


FileGetSize, fileSize, mergecap.txt
;MsgBox, fileSize=%fileSize%


if fileSize > 0
{
FileRead, errorinfo, mergecap.txt
MsgBox, 16, ERROR, %errorinfo%
ExitApp
}
ExitApp
wz520
Posts: 28
Joined: 01 Jan 2014, 21:32
Location: China

Re: 求问大神:如何让ahk脚本同时只运行一个实例

16 Dec 2015, 06:50

脚本开头添加 #SingleInstance ignore 不行吗?
User avatar
amnesiac
Posts: 186
Joined: 22 Nov 2013, 03:08
Location: Egret Island, China
Contact:

Re: 求问大神:如何让ahk脚本同时只运行一个实例

29 Jan 2016, 06:43

一般情况下,

Code: Select all

#SingleInstance ignore
就够了,如果希望即使复制一个副本也不能运行,可以在脚本开头加上下面这段代码:

Code: Select all

If WinExist("ThisisaGUIbyamnesiac")
    ExitApp
Else
    Gui, Show, Hide, ThisisaGUIbyamnesiac
这种方式非常彻底。

Return to “请求帮助”

Who is online

Users browsing this forum: No registered users and 54 guests