How to have Autohotkey 'listen' for a change to a file?

本秂侑毒 提交于 2019-12-24 03:48:10

问题


I have a text file, lets call it C:\to_run.txt. I'd like my Autohotkey script to 'listen' to this file in such a way that when it detects a change, it performs an action immediately based on the contents of the file, and then make the file blank again.

I can handle the last parts, so really I'm asking for an efficient way to detect file changes? I say efficient because my Autohotkey script is getting rather long and I don't want this listening function to hang up the rest of the script in any way.


回答1:


Check out WatchDirectory()

Just make sure you're running the latest version of AHK.

To get it up and running, first download these three scripts and save them to your /lib folder.

  • WatchDirectory.ahk
  • _Struct.ahk
  • sizeof.ahk

After that, simply point to to wherever you want to look, provide a callback function and if you want, a third param to watch for specific changes. Refer to this forum post for full documentation.

If you drop this script in its own folder, save it and run it, then save it again, it should detect changes to that script file.

#Persistent

WatchDirectory(A_ScriptDir "\|.ahk\", "Callback", 0x10)
return

Callback(param1, param2) {
    msgBox % param1 "`n" param2
}

Note however, it will fire twice whenever the file is changed. This seems to be a Windows behaviour from what I can gather.




回答2:


Assuming we are really talking of only one file to check on: Surely not as beautiful as Sidola's answer, but without the need for external libraries:

#persistent

lastFileContent := ""
setTimer, checkFile, 20
return

checkFile:
fileread newFileContent, changingDocument.txt
if(newFileContent != lastFileContent) {
    lastFileContent := newFileContent
    msgbox, content changed to: %newFileContent%
}
return

In this case, for checking on larger files, it might be better to compare MD5-checksums instead of the whole file content.

Note: I have not tested the performance implications on this. This script opens up the file 50 times per second, could be pretty hard drive consuming.



来源:https://stackoverflow.com/questions/30582633/how-to-have-autohotkey-listen-for-a-change-to-a-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!