在C:WindowsSystem32driversetc
中,我有标准hosts
文件
在C:WindowsSystem32driversetc
中,我有一个名为hosts-backup.txt
的文件
使用自动热键,当我按 ' abc1时,我想将hosts
文件替换为名为hosts-backup.txt
的文件的内容
到目前为止我写的是:
`::
Check := true
SetTimer, CheckOff, 1000 ; 1 second to type in 001
return
:*:abc1::
If Check
; Read the contents of the backup file
FileRead, Contents, C:WindowsSystem32driversetchosts-backup.txt
if not ErrorLevel ; Successfully loaded.
{
ListVars
Pause
; delete the old hots file
FileDelete, C:WindowsSystem32driversetchosts.txt
; also tried this with C:WindowsSystem32driversetchosts
; save a new copy of the hosts file with the content from the backup file
FileAppend, %Contents%, C:WindowsSystem32driversetchosts.txt
; also tried this with C:WindowsSystem32driversetchosts
Contents = ; Free the memory.
}
return
CheckOff:
Check := false
return
ListVars返回以下内容:
Global Variables (alphabetical)
--------------------------------------------------
0[1 of 3]: 0
Check[1 of 3]: 0
Contents[0 of 0]:
ErrorLevel[1 of 3]: 0
运行上述脚本时,C:WindowsSystem32driversetchosts
处的文件没有更新。
我该如何解决这个问题?
根据Blauhirn的建议更新(仍然不起作用)
`::
Check := true
SetTimer, CheckOff, -1000 ; 1 second to type in abc1
return
:*:abc1::
If Check{
; Read the contents of the backup file
FileRead, Contents, C:WindowsSystem32driversetchosts-backup.txt
if not ErrorLevel ; Successfully loaded.
{
ListVars
; delete the old hots file
FileDelete, C:WindowsSystem32driversetchosts.txt
; save a new copy of the hosts file with the content from the backup file
FileAppend, %Contents%, C:WindowsSystem32driversetchosts.txt
Contents = ; Free the memory.
}
}
return
CheckOff:
Check := false
return
这似乎是一个权限问题,如果我将脚本编译为exe并以管理员身份运行它,它会像预期的那样工作。
是否有一个简单的方法围绕这个使用自动热键?
你的这段代码:
`::
Check := true
SetTimer, CheckOff, 1000 ; 1 second to type in 001
return
CheckOff:
Check := false
return
将每1000 ms 重复设置check
为false
。"指定一个负周期,表示计时器应该只运行一次"。因为它不会在代码的任何地方自动设置回true
,所以整个计时器都是无用的。你想用它达到什么目的?Check
在前1秒内只会变成true
。因此,
If Check
FileRead, Contents, C:WindowsSystem32drivershosts-backup.txt
将在第二次结束后不做任何事情。还要注意,if
-子句只适用于下一行,因为您没有使用任何大括号{ }
。
编辑
我可能是错的,但似乎你可以省去计时器,简单地制作一个热字符串:(两个' ',因为backtick是ahk中的转义字符)
:*:``abc1::
; Read the contents of the backup file
FileRead, Contents, C:WindowsSystem32driversetchosts-backup.txt
if not ErrorLevel ; Successfully loaded.
{
ListVars
Pause
; delete the old hots file
FileDelete, C:WindowsSystem32driversetchosts.txt
; also tried this with C:WindowsSystem32driversetchosts
; save a new copy of the hosts file with the content from the backup file
FileAppend, %Contents%, C:WindowsSystem32driversetchosts.txt
; also tried this with C:WindowsSystem32driversetchosts
Contents = ; Free the memory.
}
return
在我看来,只有管理员可以编辑system32文件夹是合乎逻辑的。您是否尝试将AutoHotkey.exe更改为"始终以管理员身份运行"?http://technet.microsoft.com/en-us/magazine/ff431742.aspx