Содержание
- Frequently Asked Questions (FAQ)
- Table of Contents
- Language Syntax
- When are quotation marks used with commands and their parameters?
- When exactly are variable names enclosed in percent signs?
- When should percent signs and commas be escaped?
- General Troubleshooting
- What can I do if AutoHotkey won’t install?
- How do I restore the right-click context menu options for .ahk files?
- Why do some lines in my script never execute?
- Why doesn’t my script work on Windows xxx even though it worked on a previous version?
- How do I work around problems caused by User Account Control (UAC)?
- I can’t edit my script via tray icon because it won’t start due to an error. What do I do?
- How can I find and fix errors in my code?
- Why is the Run command unable to launch my game or program?
- Why are the non-ASCII characters in my script displaying or sending incorrectly?
- Why do Hotstrings, Send, and Click have no effect in certain games?
- How can performance be improved for games or at other times when the CPU is under heavy load?
- My antivirus program flagged AutoHotkey or a compiled script as malware. Is it really a virus?
- Common Tasks
- Where can I find the official build, or older releases?
- Can I run AHK from a USB drive?
- How can the output of a command line operation be retrieved?
- How can a script close, pause, suspend or reload other script(s)?
- How can a repeating action be stopped without exiting the script?
- How can context sensitive help for AutoHotkey commands be used in any editor?
- How to detect when a web page is finished loading?
- How can dates and times be compared or manipulated?
Frequently Asked Questions (FAQ)
Table of Contents
Language Syntax
When are quotation marks used with commands and their parameters?
Double quotes («) have special meaning only within expressions. In all other places, they are treated literally as if they were normal characters. However, when a script launches a program or document, the operating system usually requires quotes around any command-line parameter that contains spaces, such as in this example: Run, Notepad.exe «C:My DocumentsAddress List.txt» .
When exactly are variable names enclosed in percent signs?
Variable names are always enclosed in percent signs except in cases illustrated in bold below:
- In parameters that are input or output variables: StringLen, OutputVar, InputVar
- On the left side of an assignment: Var = 123abc
- On the left side of traditional (non-expression) if-statements: If Var1
- Everywhere in expressions. For example:
For further explanation of how percent signs are used, see Legacy Syntax and Dynamic Variables. Percent signs can also have other meanings:
- The percent-space prefix causes a command parameter to be interpreted as an expression.
- Escaped percent signs ( `% ) and percent signs in quoted literal strings have no special meaning (they are interpreted as literal percent signs).
When should percent signs and commas be escaped?
Literal percent signs must be escaped by preceding them with an accent/backtick. For example: MsgBox The current percentage is 25`%. Literal commas must also be escaped ( `, ) except when used in MsgBox or the last parameter of any command (in which case the accent is permitted but not necessary).
When commas or percent signs are enclosed in quotes within an expression, the accent is permitted but not necessary. For example: Var := «15%» .
General Troubleshooting
What can I do if AutoHotkey won’t install?
7-zip Error: Use 7-zip or a compatible program to extract the setup files from the installer EXE, then run setup.exe or Installer.ahk (drag and drop Installer.ahk onto AutoHotkeyU32.exe).
AutoHotkey’s installer comes packaged as a 7-zip self-extracting archive which attempts to extract to the user’s Temp directory and execute a compiled script. Sometimes system policies or other factors prevent the files from being extracted or executed. Usually in such cases the message «7-zip Error» is displayed. Manually extracting the files to a different directory may help.
Setup hangs: If the setup window comes up blank or not at all, try one or both of the following:
- Hold Ctrl or Shift when the installer starts. If you get a UAC prompt, hold Ctrl or Shift as you click Yes/Continue. You should get a prompt asking whether you want to install with default options.
- Install using command line options. If you have manually extracted the setup files from the installer EXE, use either setup.exe /S or AutoHotkeyU32.exe Installer.ahk /S .
Other: The suggestions above cover the most common problems. For further assistance, post on the forums.
How do I restore the right-click context menu options for .ahk files?
Normally if AutoHotkey is installed, right-clicking an AutoHotkey script (.ahk) file should give the following options:
- Run Script
- Compile Script (depending on the Install script compiler installation option)
- Edit Script
- Run as administrator (if UAC was enabled when AutoHotkey was installed)
- Run with UI Access (if the option was enabled during installation)
Sometimes these options are overridden by settings in the current user’s profile, such as if Open With has been used to change the default program for opening .ahk files. This can be fixed by deleting the following registry key:
This can be done by applying this registry patch.
It may also be necessary to repair the default registry values, either by reinstalling AutoHotkey or by running AutoHotkey Setup (from the Start menu) and selecting apply near the top of the window.
Why do some lines in my script never execute?
Any lines you want to execute immediately when the script starts should appear at the top of the script, prior to the first hotkey, hotstring, or Return. For details, see auto-execute section.
Also, a hotkey that executes more than one line must list its first line beneath the hotkey, not on the same line. For example:
Why doesn’t my script work on Windows xxx even though it worked on a previous version?
There are many variations of this problem, such as:
- I’ve upgraded my computer/Windows and now my script won’t work.
- Hotkeys/hotstrings don’t work when a program running as admin is active.
- Some windows refuse to be automated (e.g. Device Manager ignores Send).
If you’ve switched operating systems, it is likely that something else has also changed and may be affecting your script. For instance, if you’ve got a new computer, it might have different drivers or other software installed. If you’ve also updated to a newer version of AutoHotkey, find out which version you had before and then check the changelog and compatibility notes.
SoundGet, SoundSet, SoundGetWaveVolume and SoundSetWaveVolume behave differently on Vista and later than on earlier versions of Windows. In particular, device numbers are different and some components may be unavailable. Behaviour depends on the audio drivers, which are necessarily different to the ones used on XP. The soundcard analysis script can be used to find the correct device numbers.
Also refer to the following question:
How do I work around problems caused by User Account Control (UAC)?
By default, User Account Control (UAC) protects «elevated» programs (that is, programs which are running as admin) from being automated by non-elevated programs, since that would allow them to bypass security restrictions. Hotkeys are also blocked, so for instance, a non-elevated program cannot spy on input intended for an elevated program.
UAC may also prevent SendPlay and BlockInput from working.
Common workarounds are as follows:
- Enable the Add ‘Run with UI Access’ to context menus option in AutoHotkey Setup. This option can be enabled or disabled without reinstalling AutoHotkey by re-running AutoHotkey Setup from the Start menu. Once it is enabled, launch your script file by right-clicking it and selecting Run with UI Access, or use a command line like «AutoHotkeyU32_UIA.exe» «Your script.ahk» (but include full paths).
- Run the script as administrator. Note that this also causes any programs launched by the script to run as administrator, and may require the user to accept an approval prompt when launching the script.
- Disable the local security policy «Run all administrators in Admin Approval Mode» (not recommended).
- Disable UAC completely. This is not recommended, and is not feasible on Windows 8 or later.
I can’t edit my script via tray icon because it won’t start due to an error. What do I do?
You need to fix the error in your script before you can get your tray icon back. But first, you need to find the script file.
Look for AutoHotkey.ahk in the following directories:
- Your Documents (or My Documents) folder.
- The directory where you installed AutoHotkey, usually C:Program FilesAutoHotkey. If you are using AutoHotkey without having installed it, look in the directory which contains AutoHotkey.exe.
If you are running another AutoHotkey executable directly, the name of the script depends on the executable. For example, if you are running AutoHotkeyU32.exe, look for AutoHotkeyU32.ahk. Note that depending on your system settings the «.ahk» part may be hidden, but the file should have an icon like
You can usually edit a script file by right clicking it and selecting Edit Script. If that doesn’t work, you can open the file in Notepad or another editor.
If you launch AutoHotkey from the Start menu or by running AutoHotkey.exe directly (without command line parameters), it will look for a script in one of the locations shown above. Alternatively, you can create a script file (something.ahk) anywhere you like, and run the script file instead of running AutoHotkey.
How can I find and fix errors in my code?
For simple scripts, see Debugging a Script. To show contents of a variable, use MsgBox or ToolTip. For complex scripts, see Interactive Debugging.
Why is the Run command unable to launch my game or program?
Some programs need to be started in their own directories (when in doubt, it is usually best to do so). For example:
If the program you are trying to start is in %A_WinDir%System32 and you are using AutoHotkey 32-bit on a 64-bit system, the File System Redirector may be interfering. To work around this, use %A_WinDir%SysNative instead; this is a virtual directory only visible to 32-bit programs running on 64-bit systems.
Why are the non-ASCII characters in my script displaying or sending incorrectly?
Short answer: Save the script as UTF-8 with BOM.
Although AutoHotkey supports Unicode text, it is optimized for backward-compatibility, which means defaulting to the ANSI encoding rather than the more internationally recommended UTF-8. AutoHotkey will not automatically recognize a UTF-8 file unless it begins with a byte order mark.
In other words, UTF-8 files which lack a byte order mark are misinterpreted, causing non-ASCII characters to be decoded incorrectly. To resolve this, save the file as UTF-8 with BOM or add the /CP65001 command line switch.
To save as UTF-8 with BOM in Notepad, select UTF-8 from the Encoding drop-down in the Save As dialog.
To read other UTF-8 files which lack a byte order mark, use FileEncoding UTF-8-RAW , the *P65001 option with FileRead, or «UTF-8-RAW» for the third parameter of FileOpen(). The -RAW suffix can be omitted, but in that case any newly created files will have a byte order mark.
Note that INI files accessed with the standard INI commands do not support UTF-8; they must be saved as ANSI or UTF-16.
Why do Hotstrings, Send, and Click have no effect in certain games?
Not all games allow AHK to send keys and clicks or receive pixel colors.
But there are some alternatives, try all the solutions mentioned below. If all these fail, it may not be possible for AHK to work with your game. Sometimes games have a hack and cheat prevention measure, such as GameGuard and Hackshield. If they do, there is a high chance that AutoHotkey will not work with that game.
Use SendPlay via the SendPlay command, SendMode Play and/or the hotstring option SP.
Note: SendPlay may have no effect at all on Windows Vista or later if User Account Control is enabled, even if the script is running as an administrator.
Increase SetKeyDelay. For example:
Try ControlSend, which might work in cases where the other Send modes fail:
Try the down and up event of a key with the various send methods:
Try the down and up event of a key with a Sleep between them:
How can performance be improved for games or at other times when the CPU is under heavy load?
If a script’s Hotkeys, Clicks, or Sends are noticeably slower than normal while the CPU is under heavy load, raising the script’s process-priority may help. To do this, include the following line near the top of the script:
My antivirus program flagged AutoHotkey or a compiled script as malware. Is it really a virus?
Although it is certainly possible that the file has been infected, most often these alerts are false positives, meaning that the antivirus program is mistaken. One common suggestion is to upload the file to an online service such as virustotal or Jotti and see what other antivirus programs have to say. If in doubt, you could send the file to the vendor of your antivirus software for confirmation. This might also help us and other AutoHotkey users, as the vendor may confirm it is a false positive and fix their product to play nice with AutoHotkey.
False positives might be more common for compiled scripts which have been compressed, such as with UPX (default for AutoHotkey 1.0 but not 1.1) or MPRESS (optional for AutoHotkey 1.1). As the default AutoHotkey installation does not include a compressor, compiled scripts are not compressed by default.
Common Tasks
Where can I find the official build, or older releases?
Can I run AHK from a USB drive?
Note that when you compile a script that uses auto-included function libraries, AutoHotkey.exe and the Lib folder must be up one level from Ahk2Exe.exe (e.g. AutoHotkey.exe vs CompilerAhk2Exe.exe). Also note that Ahk2Exe saves settings to the following registry key: HKCUSoftwareAutoHotkeyAhk2Exe . The compiler itself (Ahk2Exe) is not needed to run scripts.
How can the output of a command line operation be retrieved?
Testing shows that due to file caching, a temporary file can be very fast for relatively small outputs. In fact, if the file is deleted immediately after use, it often does not actually get written to disk. For example:
To avoid using a temporary file (especially if the output is large), consider using the Shell.Exec() method as shown in the examples for the Run command.
How can a script close, pause, suspend or reload other script(s)?
First, here is an example that closes another script:
To suspend, pause or reload another script, replace the last line above with one of these:
How can a repeating action be stopped without exiting the script?
To pause or resume the entire script at the press of a key, assign a hotkey to the Pause command as in this example:
To stop an action that is repeating inside a Loop, consider the following working example, which is a hotkey that both starts and stops its own repeating action. In other words, pressing the hotkey once will start the Loop. Pressing the same hotkey again will stop it.
How can context sensitive help for AutoHotkey commands be used in any editor?
How to detect when a web page is finished loading?
With Internet Explorer, perhaps the most reliable method is to use DllCall() and COM as demonstrated at www.autohotkey.com/forum/topic19256.html. On a related note, the contents of the address bar and status bar can be retrieved as demonstrated at www.autohotkey.com/forum/topic19255.html.
Older, less reliable method: The technique in the following example will work with MS Internet Explorer for most pages. A similar technique might work in other browsers:
How can dates and times be compared or manipulated?
The EnvAdd command can add or subtract a quantity of days, hours, minutes, or seconds to a time-string that is in the YYYYMMDDHH24MISS format. The following example subtracts 7 days from the specified time: EnvAdd, VarContainingTimestamp, -7, days .
To determine the amount of time between two dates or times, see EnvSub, which gives an example. Also, the built-in variable A_Now contains the current local time. Finally, there are several built-in date/time variables, as well as the FormatTime command to create a custom date/time string.
Источник
#1
Отправлено 23 January 2023 — 12:16
Доброго времени суток, друзья! Проблема заключается в том, что не могу запустить уже готовый скрипт АНК для игры. Все было сделано по инструкции, ну так вот, углубляемся. При запуске выдает ошибку «7-Zip Error», пройдясь почти по всем видео роликам на YouTube, подходящего ничего не нашел. Есть кто знает как решить эту проблему, буду очень рад.
-
0
- Наверх
#2
Lawrence Gutierrez
Отправлено 23 January 2023 — 12:48
-
0
[HLS] — Санитар [2/10] — при Даниил Бебякин. [ПСЖ]
[Vagos] — Вертификадо [4/10] — при Ангелина Кот. [3/3]
[LS News] — Репортёр [2/6] — при Редрик Шухарт [ПСЖ]
[Aztecas] Тесорерро [8/10] — при Екатерина Дмитриева [ПСЖ]
[RM] — Вор [8/10] — при Nikita Fedylov [Смена Лидера]
[RM] — Вор в законе [9/10] — при Джон Скофилд [На данный момент]

- Наверх
#3
Daniel Morgan
Daniel Morgan
- ГородМосква
- Достижения:Поставил на место Милану Памперсон и показал чего она стоит!
Отправлено 23 January 2023 — 12:55
Запусти от имени администратора и вуаля (Но это не точно)
-
0
Трудовая книжка:
Документ гражданина:
- Наверх
#4
Никита Локинет
Никита Локинет
-
- [A]Администратор
-
- 1474 сообщений
Ваш статус отображается с вашими сообщениями
Отправлено 23 January 2023 — 16:59
Вероятно Вы извлекали файлы установщика WinRAR. Он иногда ломает АНК.
Воспользуйтесь программой 7-Zip для Windows. Она с открытым сходным кодом, поэтому всё должно быть нормально.
-
0

- Наверх
#5
Maксим Вoльский
Maксим Вoльский
-
- [B]Лидер Ballas
-
- 1444 сообщений
ᴍᴏɴᴇʏ ᴄᴀɴ’ᴛ ʙᴜʏ ʟɪꜰᴇ
-
Достижения:Счастье.
======================
ʟᴇᴀᴅᴇʀ ʜᴏsᴘɪᴛᴀʟ ʟᴠ.
[12.12.2021 — 12.01.2022]
======================
ʟᴇᴀᴅᴇʀs ʙᴀʟʟᴀs ɢᴀɴɢ.
[14.01.2023 — xx.xx.2023]
======================
Отправлено 23 January 2023 — 17:52
Скачай сначало приложение само для того чтобы использовать AHK файлы, после скачай сам файл с форума или где тебе там нужно и запусти просто.
-
0
- Наверх
#6
OS:EF v.2.0
OS:EF v.2.0
-
-
[IC]Модератор IC
-
- 1176 сообщений
Падшая
- ГородАнгелов
-
Достижения:Правда думаете, что кому-то интересно какие лидерки Вы стояли?
Нет ничего более позорного для игрока, чем писать про свои лидерки/админки здесь.
Отправлено 23 January 2023 — 18:28
Не используйте AHK, не позорьте гены.
-
1
А что, если мы все пали?
- Наверх
#7
Никита Мерoлов
Отправлено 23 January 2023 — 21:47
для чего ахк?
изначально надо было для ПД, но уже ушел от туда. но а проблему бы решить.
-
0
- Наверх
#8
Lawrence Gutierrez
Отправлено 23 January 2023 — 22:27
изначально надо было для ПД, но уже ушел от туда. но а проблему бы решить.
удали ахк, не позорься
-
0
[HLS] — Санитар [2/10] — при Даниил Бебякин. [ПСЖ]
[Vagos] — Вертификадо [4/10] — при Ангелина Кот. [3/3]
[LS News] — Репортёр [2/6] — при Редрик Шухарт [ПСЖ]
[Aztecas] Тесорерро [8/10] — при Екатерина Дмитриева [ПСЖ]
[RM] — Вор [8/10] — при Nikita Fedylov [Смена Лидера]
[RM] — Вор в законе [9/10] — при Джон Скофилд [На данный момент]

- Наверх
#9
Randy Torres
Randy Torres
- Городлюбви…
-
Достижения:[Заместитель главного врача Hospital LV- 26.03.2022 — 07.04.2022]
[Главный Врач Hospital LV — 07.04.2022 — 19.04.2022]
Отправлено 24 January 2023 — 19:09
Комментарии по типу «Удали АНК», «Не используй АНК, не позорься», «АНК для слабых» от типа «крутых» ребят с МЭТЭА РЭПЭ сервера. Игнорируйте таких людей и их «супер мнение». Играйте в свое удовольствие!
-
2
*Наше РП легендарное*
Трудовая книга
Биография
- Наверх
#10
Oлег Дихтеренко
Oлег Дихтеренко
- ГородМиколаев
-
Достижения:.
▬▬▬▬▬▬▬▬▬▬▬
Leader Hospital LV [25.04.2022 — 25.05.2022]
▬▬▬▬▬▬▬▬▬▬▬
Leader LS News [13.07.2022 — 13.08.2022]
▬▬▬▬▬▬▬▬▬▬▬
Отправлено 24 January 2023 — 22:47
Комментарии по типу «Удали АНК», «Не используй АНК, не позорься», «АНК для слабых» от типа «крутых» ребят с МЭТЭА РЭПЭ сервера. Игнорируйте таких людей и их «супер мнение». Играйте в свое удовольствие!
С вами согласен, так как в некоторых фракциях необходимо использовать ахк, если все же такие люди останутся, пускай помогут создателю проекта и напишет код с биндером на примере когда пишешь /aheal id и сробативает биндером ч отыгровками, тем самым заменяя ахк
-
0
- Наверх
#11
Jessica Cardoso
Jessica Cardoso
- Достижения:Психически здоровый человек.
Отправлено 25 January 2023 — 06:08
С вами согласен, так как в некоторых фракциях необходимо использовать ахк, если все же такие люди останутся, пускай помогут создателю проекта и напишет код с биндером на примере когда пишешь /aheal id и сробативает биндером ч отыгровками, тем самым заменяя ахк
Таким же успехом можно полностью забыть об рп и всю его составляющее свести на игру командами, удалив при этом /me, /todo, /try и /do (Ну или оставить /me, чтобы писать /me Процесс… (Ирония))
-
0
- Наверх
#12
Алихан Импалов
Алихан Импалов
-
Достижения:Leader East Side Ballas 20.03.21 — 18.04.21
______________________________________________
Leader Varrios Los Aztecas 02.08.21 — 02.09.21
______________________________________________
Leader La Cosa Nostra 18.12.22 — 18.01.23
Отправлено 25 January 2023 — 20:51
сочувствую тем кто думает что ахк только для рпшки
-
2
- Наверх
The AHK script below should use 7-zip to extract a folder when ctrl+ALT+Left is pressed. When you manually right-click on a folder and then type «7eee» and then press enter, the folder extracts. I’d like to mimic this without the right-click and instead use the keyboard shortcut. I tried to do this two ways:
;alt + ctrl
!^LButton::
blockinput on
send {LButton}{RButton}7eee{enter}
blockinput Off
return
I also tried:
;alt + ctrl
!^LButton::
temp = %clipboard%
KeyWait, LButton, D
send {LButton}
sleep,100
Send, {Ctrl Down}c{Ctrl Up}
file = %clipboard% ;get file address
clipboard = %temp% ;restore clipboard
outdir := getdir(file)
if (A_Is64bitOS = 1)
{
runwait, "C:Program Files7-Zip7z.exe" x "%file%" -o"%outdir%" -y,,hide
}
else
{
runwait, "C:Program Files (x86)7-Zip7z.exe" x "%file%" -o"%outdir%" -y,,hide
}
msgbox, 7zip has finished extracting "%file%".
return
getdir(input)
{
SplitPath, input,,parentdir,,filenoext
final = %parentdir%%filenoext%
return final
}
EDIT:
I have found something that works:
#IfWinActive, AHK_EXE Explorer.exe
^e::
temp = %clipboard%
Send, {Ctrl Down}c{Ctrl Up}
file = %clipboard% ;get file address
clipboard = %temp% ;restore clipboard
outdir := getdir(file)
if (A_Is64bitOS = 1)
{
runwait, "C:Program Files7-Zip7z.exe" x "%file%" -o"%outdir%" -y,,hide
}
else
{
runwait, "C:Program Files (x86)7-Zip7z.exe" x "%file%" -o"%outdir%" -y,,hide
}
msgbox, 7zip has finished extracting "%file%".
return
getdir(input)
{
SplitPath, input,,parentdir,,filenoext
final = %parentdir%%filenoext%
return final
}
#If
But I do not like the message box and I wish there were a progress bar or indication that it is in the process of extracting.
Hello,
I gave up on getting this done myself. This is a continuation of this [Create Zip-folder from highlighted/selected files in windows explorer], although I am now trying to do the opposite, that is to unzip a zipped folder into a folder of the same name, located at the same directory the zip is located in. I’ve tried using windows native methods for zipping, but had no success implementing this successfully. Up to 70% of the expected files were missing in the output directory, so I am back to just using 7zip instead. I suspect my implementation wasn’t perfectly correct, but right now I’d rather have a functional version with dependencies rather than none.
Anyways, I’ve tried reading through the docs, but I don’t seem to understand how this actually works, and I can’t get it to work ._.
Using the code below as a demo will yield in a command window asking if
Numpad9::
sevenZip := A_ProgramFiles "7-zip7z.exe"
Run % sevenZip " e " quote("D:DokumenteCSA00 AAA Dokumente00 AAA HSRWGeneralAHK scriptsProjectsDevelopmentFiles2ziparchive.zip")
return
quote(str)
{
return """" str """"
}
As a tangential question:
While experimenting, I’ve extracted files into a directory they already existed in. The command prompt then asked what to do, and amongst other things, I’ve checked the wonderful «always hide this window» of the 7z-command-window, meaning it disappears always. I don’t know how to revert that, since I cannot open the commandwindow the same way anymore, as it autohides from me now ¯_(ツ)_/¯
Thank you.
Sincerely,
~Gw
Current Code:
This would need to be implemented at line 8ff.
fFileZipper()
{
static foldername
static
foldername:=""
Store:=ClipboardAll
FilesToZip:=fClip() ; because we are taking text, this seems to muddy the clipboard? weird, that's exactly what it should prevent
if InStr(FilesToZip,".zip")
{
SplitPath, FilesToZip,ZipName,ZipDir,,Name_no_ext
CurrDir:=fGetActiveFolderPath()
MsgBox, %FilesToZip%`nZN:%ZipName%`nZD:%ZipDir%`nZN2:%Name_no_ext%`nCD: %CurrDir%
;UnzPath:=CurrDir . "/" . Name_no_ext
;MsgBox, % UnzPath
Run % sevenZip " e " FilesToZip
; this is the zipping code used below, just copied here for reference while working. screen is too small ._.
;sevenZip := A_ProgramFiles "7-zip7z.exe" sevenZip := A_ProgramFiles "7-zip7z.exe"
;fileList := ""
;FilesToZip:=fClip() ;; fClip is just a much more reliable way of using the clipboard, and in this case effectively only copies the selected file paths onto the clipboard, and then outputs them to this variable, reverting the last clipboard change . It is synonymous to pressing Ctrl+C before running this code without this step, with the exception that I would loose the original clipboard.
;loop parse, % RTrim(FilesToZip, "`r`n"), `n, `r
;fileList .= " " quote(dir := A_LoopField)
;SplitPath dir,, dir
;fileList := StrReplace(fileList, dir "")
;Run % sevenZip " a -tzip " quote(foldername ".zip") fileList, % dir
;WinWaitActive ahk_exe 7z.exe
;WinMinimize
;Clipboard:=Store
}
else
{
gui_control_options := "xm w220 " . cForeground . " -E0x200" ; remove border around edit field
Gui, Margin, 16, 16
Gui, +AlwaysOnTop -SysMenu -ToolWindow -caption +Border
cBackground := "c" . "1d1f21"
cCurrentLine := "c" . "282a2e"
cSelection := "c" . "373b41"
cForeground := "c" . "c5c8c6"
cComment := "c" . "969896"
cRed := "c" . "cc6666"
cOrange := "c" . "de935f"
cYellow := "c" . "f0c674"
cGreen := "c" . "b5bd68"
cAqua := "c" . "8abeb7"
cBlue := "c" . "81a2be"
cPurple := "c" . "b294bb"
Gui, Color, 1d1f21, 373b41,
Gui, Font, s11 cWhite, Segoe UI
gui, add, text,xm ym, Enter Name of zipped directory
Gui, add, Edit, %gui_control_options% -VScroll vfoldername
Gui, Font, s10 cWhite, Segoe UI
gui, add, Checkbox, vvCheckShell, Use native shell instead of 7zip? (less reliable)
Gui, add, Button, default gSubmitFileZipper h0 w0 xs-50 ys -50
Hotkey, Esc, gui_destroy_FileZipper, On ; FileZipper || Escape Key
gui, show,, FileZipper
}
return
gui_destroy_FileZipper:
Hotkey, Esc, gui_destroy_FileZipper, Off ; FileZipper || Escape Key
gui, destroy
return
SubmitFileZipper:
gui, submit
gui, destroy
if vCheckShell ; this is the more reliable, albeit much slower version
{
CurrDir:=fGetActiveFolderPath()
sZip:=CurrDir . "" . foldername . ".zip"
Zip(FilesToZip,sZip)
Clipboard:=""
Clipboard:=Store
}
else
{
fileList := ""
FilesToZip:=fClip() ;; fClip is just a much more reliable way of using the clipboard, and in this case effectively only copies the selected file paths onto the clipboard, and then outputs them to this variable, reverting the last clipboard change . It is synonymous to pressing Ctrl+C before running this code without this step, with the exception that I would loose the original clipboard.
sevenZip := A_ProgramFiles "7-zip7z.exe"
loop parse, % RTrim(FilesToZip, "`r`n"), `n, `r
fileList .= " " quote(dir := A_LoopField)
SplitPath dir,, dir
fileList := StrReplace(fileList, dir "")
Run % sevenZip " a -tzip " quote(foldername ".zip") fileList, % dir
WinWaitActive ahk_exe 7z.exe
WinMinimize
Settimer, NotifyZippingFinished, 250
Clipboard:=Store
}
NotifyZippingFinished:
if !WinExist("C:Program Files7-zip7z.exe")
{
SetTimer, NotifyZippingFinished, off
Notify().AddWindow("Directory`n"""foldername . """:`nZipping Complete",{Title:"FileZipper",TitleColor:"0x000000",Time:5000,Color:"0x000000",Background:"0xFFFFFF",TitleSize:10,Size:10,ShowDelay:0}) ;,Buttons:"Open"})
}
return
}
#If WinActive("FileZipper")
^Backspace::Send ^+{Left}{Backspace} ; Windows Explorer: File Zipper|| Delete last word
#If
quote(str)
{
return """" str """"
}
return
Zip(FilesToZip,sZip)
{
FileArray:=StrSplit(FilesToZip,"`n")
MaxEntries:=FileArray.MaxIndex()
If Not FileExist(sZip)
CreateZipFile(sZip)
psh:=ComObjCreate( "Shell.Application" )
pzip:=psh.Namespace( sZip )
if InStr(FileExist(FilesToZip), "D")
FilesToZip .= SubStr(FilesToZip,0)="" ? "*.*" : "*.*"
loop, %MaxEntries%
{
FilesToZip:=FileArray[A_Index]
zipped++
CurrFile:=strReplace(FilesToZip,"`r")
CurrFile:=strReplace(CurrFile,"`n")
ToolTip Zipping %CurrFile%
;pzip.CopyHere( CurrFile, 4|8|16|1024)
pzip.CopyHere( CurrFile, 4|8|16)
}
ToolTip
}
CreateZipFile(sZip)
{ ;*[ConstantRun]
Header1 := "PK" . Chr(5) . Chr(6)
VarSetCapacity(Header2, 18, 0)
file := FileOpen(sZip,"w")
file.Write(Header1)
file.RawWrite(Header2,18)
file.close()
}
Unz(sZip, sUnz)
{
fso := ComObjCreate("Scripting.FileSystemObject")
If Not fso.FolderExists(sUnz) ;http://www.autohotkey.com/forum/viewtopic.php?p=402574
fso.CreateFolder(sUnz)
psh := ComObjCreate("Shell.Application")
zippedItems := psh.Namespace( sZip ).items().count
psh.Namespace( sUnz ).CopyHere( psh.Namespace( sZip ).items, 4| )
Loop {
sleep 50
unzippedItems := psh.Namespace( sUnz ).items().count
ToolTip Unzipping in progress..
IfEqual,zippedItems,%unzippedItems%
break
}
ToolTip
}
Работа программы 7-Zip осуществляется благодаря взаимодействию команд и операторов. Для этого требуются подходящие условия, что обеспечивается не всегда. Поэтому возникает ошибка контрольной суммы и другие проблемы при распаковке архива приложением 7-Zip. В этой статье вы найдете решение частых неполадок в работе архиватора.
Ошибка контрольной суммы CRC
Скачивание заархивированного файла может завершиться тем, что пользователь при запуске получит сообщение: «Ошибка контрольной суммы». Другое название проблемы: «Ошибка CRC сжатых данных».
Такая ошибка возникает из-за того, что скачивание архива сопровождалось потерей пакетов. Во время загрузки происходили ошибки, что актуально для нестабильного интернета, когда теряется связь.
Чаще с такой проблемой сталкиваются пользователи с большими файлами, загрузка которых длится несколько часов. При этом объем документов совпадает, но только округленные значения, так как несколько битов все равно потеряно.
Как исправить:
- Проблему с распаковкой 7-Zip архива можно решить до возникновения ошибки, используя программное обеспечение Download Master. Потерянный пакет вынуждает начинать загрузку заново.
- Другой вариант – восстановить архив. Рекомендуется воспользоваться архиватором WinRAR. Если расширение файла не поддерживается, то подойдет программа Universal Extractor.
WinRAR удобен тем, что имеет встроенную функцию для восстановления архивов, где некоторое количество пакетов потеряно.
Как восстановить архив
- Запустите WinRAR, через интерфейс выберите Tools, а затем – Repair archive.
- Открыть поврежденный архив не получится, поэтому создайте новый и перейдите в папку к файлу с потерянными пакетами.
- Перед восстановлением щелкните один раз по названию.
- Иногда требуется указать путь для восстановленного архива и его формат. Расширение должно оставаться тем же, что было до потери информации. Если все указано верно, нажмите ОК и дождитесь окончания работы WinRAR.
Если приложение справится и ошибка архива 7-Zip исчезнет, то загружать файл заново не придется.
Проблема может возникать постоянно. Для решения систематического сбоя проверьте оперативную память и жесткий диск программным обеспечением Aida.
Отказ в доступе
Часто пользователи при добавлении новых файлов через меню 7-Zip сталкиваются с ошибкой «Отказано в доступе». Существует 3 варианта решения:
- Проверить корректность работы антивируса. Не блокирует ли он файл, запрещая активировать архив на компьютере. Достаточно отключить программу и открыть документ.
- Архиватор 7-Zip предполагает установку паролей. Возможно, требование ввести ключ от файла не отображается, а пользователь сразу получает отказ доступа. Единственный способ проверить это – обратиться к правообладателю сжатого материала.
- Если файл открывается не из администраторской директории, то нужно поменять учетную запись или открыть архив через главного пользователя.
Иные проблемы говорят о том, что файл битый. Попробуйте воспользоваться не 7-Zip, а другим распаковщиком или просто скачайте документ заново.
Unsupported command 7 Zip
Ошибка «Unsupported command» в 7-Zip возникает совместно с указанием места расположения файла. Но локальная ссылка не представляет ничего интересного, так как решение проблемы кроется не в ней.
Установка архиватора 7-Zip заканчивается тем, что пользователь устанавливает связь между программой и сжатыми данными. Для этого нужно указать ярлык программы.
Правильный выбор – 7zFM, а не 7zG. В последнем случае программе отправляется команда открыть файл через нерабочий ярлык.
Отменить привязку распаковщика к формату можно через интерфейс 7-Zip:
- Откройте файловый менеджер через меню «Пуск».
- «Сервис» – «Настройки».
- Во вкладке «Система» снимите галочку в окошке рядом с проблемным форматом. Щелкните ОК.
Теперь можно попробовать запустить документ заново.
Не удается открыть файл
Пользователь может получить сообщение, что 7-Zip не удалось открыть файл, который сохранен как архив. Ошибка носит функциональный характер, связанный с основным недостатком распаковщика.
Архивный файл открывается через контекстное меню.
Если это не дало результата, попробуйте следующие варианты:
- Воспользоваться аналогами, например WinRAR. Иногда достаточно переустановить 7-Zip, и ошибка исчезает.
- Установить на компьютер программу, восстанавливающую битые архивы, и извлечь файлы через нее.
Убедитесь, что расширение документа соответствует возможностям разархиватора.
Данные после конца блока полезных данных
Сообщение программы 7-Zip в конце распаковки: «Есть данные после конца блока полезных данных» возникает при использовании двух разных архиваторов. Запаковывались документы через WinRAR, где установлена опция «Добавить запись восстановления». Разработчики предлагают не бороться с ошибкой, а продолжать распаковывать.
Источник проблемы очевиден, если пользователь получает ошибку при распаковке через контекстное меню или интерфейс файлового менеджера. Для проверки выделите документы мышкой и перенесите в новую папку. Если сообщения нет, то и в остальных случаях его можно игнорировать.
Разработчики 7-Zip выявили связь с WinRAR после обнаружения в архиве данных, объем которых не превышает 50 Кб. Распаковщик предупреждает об этом документе, поэтому сообщение игнорируется.
Поврежденный архив
Если во время работы 7-Zip пользователь получает сообщение: «Ошибка данных», то, возможно, архив поврежден при загрузке на компьютер. Исправить проблему без использования сторонних средств нельзя. В таком случае установите программу Universal Extractor.
Приложение исправляет проблему поврежденных архивов. Поддерживаются все известные методы сжатия. Интерфейс не содержит лишних кнопок, поэтому понятен и прост.
Открыть архив удается почти всегда. Если ситуация повторилась, проверьте компьютер на вирусы, так как они могут перехватывать пакеты. Это разрушает структуру сжатого файла, делая его недоступным пользователю.
Неподдерживаемый метод
Если некоторые файлы извлечены из архива, а другие нет, то пользователь увидит ошибку, что определенный метод не поддерживается в программе 7-Zip.
Иногда быстрее воспользоваться другим распаковщиком. Если аналогов на компьютере нет, то обновите 7-Zip до последней версии.
С подобной ошибкой встречаются пользователи, скачивающие документы в формате «zipx». Новые методы, разработанные WinZip, позволяют сократить размер файла, но другим приложениям пришлось выпускать обновления, чтобы решить проблему.
Ошибки в архиваторе возникают часто, но пользователи совместно с разработчиками научились их решать и сокращать в последних версиях программы. О том, почему сайт www.7-zip.org не открывается и как получить доступ, подробно рассказывается в отдельной статье.
Обновить 7-Zip для исправления ошибок можно на официальном сайте разработчика. Но сейчас пользователи испытывают трудности с доступом к ресурсу, поэтому скачайте архиватор 7-Zip бесплатно на нашем сайте.
Загрузка…
Щелчок правой кнопкой мыши на заархивированной папке, нажатие 7 (выбирает подменю 7-zip), нажатие e три раза, а затем нажатие Enter извлекает папку. Я пытался автоматизировать это, но он просто открывает заархивированную папку в новом окне:
#IfWinActive, AHK_EXE Explorer.exe
^e::
blockinput on
SetKeyDelay, 5000
send {RButton}
SetKeyDelay, 5000
send 7
SetKeyDelay, 5000
send e
SetKeyDelay, 5000
send e
SetKeyDelay, 5000
send e
SetKeyDelay, 5000
send {enter}
blockinput Off
return
1 ответ
Во-первых, SetKeyDelay нужно вызывать только один раз. Возможно, вы хотели использовать Sleep.
Я заработал без SetKeyDelay и без необходимости наводить курсор на файл, потому что я использовал клавишу «меню» вместо щелчка правой кнопкой мыши. Надеюсь это поможет.
BlockInput Send
#IfWinActive, ahk_exe Explorer.exe
^e::
Send {AppsKey}7eee{Enter}
Return
0
D. Pardal
25 Июл 2020 в 22:36









