Autohotkey 1.1.33.02

4 — Running Programs & Websites

mspaint.exe, calc.exe, script.ahkRunhttps://www.autohotkey.com/

; Run a program. Note that most programs will require a FULL file path:
Run, %A_ProgramFiles%\Some_Program\Program.exe

; Run a website:
Run, https://www.autohotkey.com

There are some other advanced features as well, such as command line parameters and CLSID. If you want to learn more about that stuff, visit the Run page.

Here are a few more samples:

; Several programs do not need a full path, such as Windows-standard programs:
Run, notepad.exe
Run, mspaint.exe

; Run the "My Documents" folder using a :
Run, %A_MyDocuments%

; Run some websites:
Run, https://www.autohotkey.com
Run, https://www.google.com

For more in-depth information and examples, check out the Run page.

Установка AutoHotkey

Прежде чем вы сможете протестировать некоторые скрипты или создать свои собственные, вам нужно установить AutoHotkey. Посетите главную страницу AHK, нажмите Скачать на правой стороне, и выберите монтажник захватить самую простую версию для установки. Запустите диалог быстрой установки, и AutoHotkey будет запущен и готов к работе!

Теперь только что установленная программа обрабатывает выполнение сценариев, которые вы пишете на языке AutoHotkey, но у вас еще нет запущенных сценариев! Чтобы создать новый, убедитесь, что AutoHotkey запущен (откройте меню «Пуск» и введите AutoHotkey запустить программу), затем щелкните правой кнопкой мыши в любом месте на рабочем столе или в любом другом удобном месте и выберите New> AutoHotkey Script. Назовите это что-нибудь полезное и убедитесь, что файл заканчивается .АХК, или это не будет работать правильно.

Если вы собираетесь писать несколько сценариев для AutoHotkey, неплохо бы обновить ваш текстовый редактор из мягкого блокнота

, Notepad ++ — отличный бесплатный вариант, который рекомендуется для этой цели

Обратите внимание, что вы можете открыть свой текстовый редактор, ввести код и просто сохранить его как файл, оканчивающийся на .АХК и вы достигнете того же результата, что и вышеописанный метод

Теперь, когда у вас есть программное обеспечение для запуска сценариев, вы можете загрузить код, написанный другими, для автоматизации всех видов задач. Чтобы сохранить скрипт, просто загрузите его как .АХК файл и сохранить его, где вы хотите.

Возможно, вы захотите, чтобы некоторые из этих сценариев запускались сразу после загрузки компьютера, поэтому вам не нужно каждый раз запускать их вручную. Для этого скопируйте и вставьте .АХК файлы в папку «Автозагрузка», набрав оболочка: запуск в меню «Пуск» или перейдя по следующему адресу:

Это обеспечит их запуск сразу после запуска, поэтому вы не пытаетесь использовать комбинации клавиш и ничего не получаете!

Что такое AutoHotkey

Скрипты AutoHotkey — отличный способ автоматизировать некоторые действия на компьютере, но на первый взгляд эта программа может показаться сложной. Не волнуйтесь — начать гораздо проще, чем кажется! Читайте дальше, чтобы увидеть как пользоваться AutoHotkey.

Программа AutoHotkey позволяет создавать макросы и скрипты выполняющие самые разнообразные действия, которые можно привязать к любым клавишам. Программа отлично подходит для автоматизации и ускорения действий. Может применяться при вводе текста, в играх, обычной работе в операционной системе.

Скрипты могут иметь графический интерфейс для показа информации и ввода настроек.

У AutoHotkey очень развитый скриптовый язык, но вам необязательно его изучать — вы можете воспользоваться готовыми скриптами.

Автоматизируйте ваши повторяющиеся задачи с помощью AutoHotkey

AutoHotkey способен на многое, и сказать, что этот урок едва царапает поверхность, было бы преуменьшением. В прошлом мы рассмотрели много важных скриптов AutoHotkey, и есть много других, которые могут сделать вашу жизнь проще.

Умение создавать собственные сценарии AutoHotkey также является отличным навыком, хотя стоит проверить руководство по сочетанию клавиш Windows Ultimate.

Сочетания клавиш Windows 101: полное руководство

Сочетания клавиш Windows 101: полное руководствоСочетания клавиш могут сэкономить часы времени. Освойте универсальные сочетания клавиш Windows, приемы клавиатуры для конкретных программ и несколько других советов, чтобы ускорить вашу работу.
Прочитайте больше
чтобы увидеть, если ярлык, который вы хотите сделать, уже существует!

Узнайте больше о: AutoHotkey, компьютерная автоматизация, сочетания клавиш.

Function Hotkeys [v1.1.20+]

One or more hotkeys can be assigned a function by simply defining it immediately after the hotkey label as in this example:

; Ctrl+Shift+O to open containing folder in Explorer.
; Ctrl+Shift+E to open folder with current file selected.
; Supports SciTE and Notepad++.
^+o::
^+e::
    editor_open_folder() {
        WinGetTitle, path, A
        if RegExMatch(path, "\*?\K(.*)\\+(?=  )", path)
            if (FileExist(path) && A_ThisHotkey = "^+e")
                Run explorer.exe /select`,"%path%"
            else
                Run explorer.exe "%path1%"
    }

: Hotstrings can also be defined this way. Multiple hotkeys or hotstrings can be stacked together to call the same function.

There must only be whitespace, comments or directives between the hotkey/hotstring labels or label and the function. Hotkey/hotstring labels defined this way are not visible to IsLabel(), Gosub or other commands; however, the ends at the first hotkey/hotstring even if it is assigned a function.

The main benefit of using a function is that local variables can be used, which avoids conflicts when two or more hotkeys use the same variable names for different purposes. It also encourages self-documenting hotkeys, like in the code above where the function name describes the hotkey.

The Hotkey command can also be used to assign a function or function object to a hotkey.

Как пользоваться

Дальше давайте переходить к практике и разбираться, где бесплатно скачать последнюю версию данного предложения, как его установить, а также как написать свой первый скрипт при помощи AutoHotkey.

Загрузка и установка

Начинать мы будем именно с установки. Тем более, что как таковой, ее здесь нет. Данная программа работает сразу после запуска. Рассмотрим, как его осуществить:

  1. Сначала мы загружаем архив с приложением, прокрутив страничку ниже и воспользовавшись кнопкой для его скачивания. Распаковываем исполняемый файл и запускаем его двойным левым кликом.
  1. Теперь нам необходимо предоставить доступ к администраторским полномочиям. В противном случае приложение не сможет корректно работать.
  1. На этом все. Наша программа установленная и теперь можно переходить непосредственно к работе с ней.

Инструкция по работе

Теперь давайте в общих чертах разберемся, как пользоваться данным приложением. Первое, что следует знать, это скриптовый язык программирования, который тут используется. Без него ни одного макроса написать, к сожалению, не получится. А сам алгоритм использования программы выглядит следующим образом:

  1. Вы пишите макрос, которым должна руководствоваться в своей работе AutoHotkey.
  2. Далее при помощи программы открываем данный скрипт и, при необходимости, преобразуем его в EXE-файл.
  3. Дальше мы можем использовать файл где угодно.

Вот так выглядит сам скрипт, а также созданный с его помощью исполняемый файл.

5 — Commands vs. Functions()

AutoHotkey has two main types of things used by the scripter to create code: Commands and functions.

A list of all commands and built-in functions can be found here.

Commands

You can tell what a command is by looking at its syntax (the way it looks). Commands do not use parentheses around the parameters like functions do. So a command would look like this:

Command, Parameter1, Parameter2, Parameter3

When using commands, you cannot squish other commands onto the same line as a previous command (exception: IfEqual). You cannot put commands inside the parameters of other commands. For example:

MsgBox, Hello Run, notepad.exe   ; Wrong
MsgBox, Hello, Run, notepad.exe  ; Wrong

MsgBox, Hello      ; Correct
Run, notepad.exe

need

You can do math in parameters if you force an expression with a single , but that will not be covered.

Functions

As stated above, functions are different because they use parentheses. A typical function looks like:

Function(Parameter1, Parameter2, Parameter3)

Functions have a few main differences:

  1. You can do math in them:
    SubStr(37 * 12, 1, 2)
    SubStr(A_Hour - 12, 2)
  2. Variables do not need to be wrapped in percent signs:
    SubStr(A_Now, 7, 2)
  3. Functions can go inside of functions:
    SubStr(A_AhkPath, InStr(A_AhkPath, "AutoHotkey"))
  4. Text needs to be wrapped in quotes:
    SubStr("I'm scripting, awesome!", 16)

A function usually return a value differently than a command does. Commands need an OutputVar parameter, functions do not. The most common way assigning the value of a function to a variable is like so:

MyVar := SubStr("I'm scripting, awesome!", 16)

This isn’t the only way, but the most common. You are using to store the return value of the function that is to the right of the operator. See Functions for more details.

In short:

; These are commands:
MsgBox, This is some text.
StringReplace, Output, Input, AutoHotKey, AutoHotkey, All
SendInput, This is awesome{!}{!}{!}

; These are functions:
SubStr("I'm scripting, awesome!", 16)
FileExist(VariableContainingPath)
Output := SubStr("I'm scripting, awesome!", 16)

a. Code blocks

Code blocks are lines of code surrounded by little curly brackets ( and ). They group a section of code together so that AutoHotkey knows it’s one big family and that it needs to stay together. They are most often used with functions and control flow statements such as If and Loop. Without them, only the first line in the block is called.

In the following code, both lines are run only if MyVar equals 5:

if (MyVar = 5)
{
    MsgBox, MyVar equals %MyVar%!!
    ExitApp
}

In the following code, the message box is only shown if MyVar equals 5. The script will always exit, even if MyVar is not 5:

if (MyVar = 5)
    MsgBox, MyVar equals %MyVar%!!
    ExitApp

This is perfectly fine since the if-statement only had one line of code associated with it. It’s exactly the same as above, but I outdented the second line so we know it’s separated from the if-statement:

if (MyVar = 5)
    MsgBox, MyVar equals %MyVar%!!
MsgBox, We are now 'outside' of the if-statement. We did not need curly brackets since there was only one line below it.

Installer Options

To silently install AutoHotkey into the default directory (which is the same directory displayed by non-silent mode), pass the parameter /S to the installer. For example:

AutoHotkey110800_Install.exe /S

A directory other than the default may be specified via the /D parameter (in the absence of /S, this changes the default directory displayed by the installer). For example:

AutoHotkey110800_Install.exe /S /D=C:\Program Files\AutoHotkey

Version: If AutoHotkey was previously installed, the installer automatically detects which version of AutoHotkey.exe to set as the default. Otherwise, the default is Unicode 32-bit or Unicode 64-bit depending on whether the OS is 64-bit. To override which version of AutoHotkey.exe is set as the default, pass one of the following switches:

  • or : ANSI 32-bit.
  • or : Unicode 64-bit (only valid on 64-bit systems).
  • : Unicode 32-bit.

For example, the following installs silently and sets ANSI 32-bit as the default:

AutoHotkey110800_Install.exe /S /A32

Uninstall: To silently uninstall AutoHotkey, pass the parameter to Installer.ahk. For example:

"C:\Program Files\AutoHotkey\AutoHotkey.exe" "C:\Program Files\AutoHotkey\Installer.ahk" /Uninstall

For AutoHotkey versions older than 1.1.08.00, use . For example:

"C:\Program Files\AutoHotkey\uninst.exe" /S

Note: Installer.ahk must be run as admin to work correctly.

Extract: Later versions of the installer include a link in the bottom-right corner to extract setup files without installing. If this function is present, the switch can be used to invoke it from the command line. For example:

AutoHotkey110903_Install.exe /D=F:\AutoHotkey /E

Restart scripts : In silent install/uninstall mode, running scripts are closed automatically, where necessary. Pass the switch to automatically reload these scripts using whichever EXE they were running on, without command line args. Setup will attempt to launch the scripts via Explorer, so they do not run as administrator if UAC is enabled.

Taskbar buttons : On Windows 7 and later, taskbar buttons for multiple scripts are automatically grouped together or combined into one button by default. The Separate taskbar buttons option disables this by registering each AutoHotkey executable as a .

: For command-line installations, specify or to enable the option and to disable it.

Run with UI Access

The installer GUI has an option «Add ‘Run with UI Access’ to context menus». This context menu option provides a workaround for common by allowing the script to automate administrative programs — without the script running as admin. To achieve this, the installer does the following:

  • Copies AutoHotkeyA32.exe, AutoHotkeyU32.exe and (if present) AutoHotkeyU64.exe to AutoHotkey*_UIA.exe.
  • Sets the uiAccess attribute in each UIA file’s embedded manifest.
  • Creates a self-signed digital certificate named «AutoHotkey» and signs each UIA file.
  • Registers the context menu option to run the appropriate exe file.

If any these UIA files are present before installation, the installer will automatically update them even if the UI Access option is not enabled.

For command-line installations, specify or to enable the option and to disable it. By default, the installer will enable the option if UAC is enabled and the UI Access context menu option was present before installation.

Scripts which need to run other scripts with UI access can simply Run the appropriate UIA.exe file with the normal .

Known limitations:

  • UIA is only effective if the file is in a trusted location; i.e. a Program Files sub-directory.
  • UIA.exe files created on one computer cannot run on other computers without first installing the digital certificate which was used to sign them.
  • UIA.exe files cannot be started via CreateProcess due to security restrictions. ShellExecute can be used instead. Run tries both.
  • UIA.exe files cannot be modified, as it would invalidate the file’s digital signature.
  • Because UIA programs run at a different «integrity level» than other programs, they can only access objects registered by other UIA programs. For example, will fail because Word is not marked for UI Access.
  • The script’s own windows can’t be automated by non-UIA programs/scripts for security reasons.
  • Running a non-UIA script which uses a mouse hook (even as simple as ) may prevent all mouse hotkeys from working when the mouse is pointing at a window owned by a UIA script, even hotkeys implemented by the UIA script itself. A workaround is to ensure UIA scripts are loaded last.

For more details, see Enable interaction with administrative programs on the archive forum.

Custom Combinations

You can define a custom combination of two keys (except joystick buttons) by using » & » between them. In the below example, you would hold down Numpad0 then press the second key to trigger the hotkey:

Numpad0 & Numpad1::MsgBox You pressed Numpad1 while holding down Numpad0.
Numpad0 & Numpad2::Run Notepad

The prefix key loses its native function: In the above example, Numpad0 becomes a prefix key; but this also causes Numpad0 to lose its original/native function when it is pressed by itself. To avoid this, a script may configure Numpad0 to perform a new action such as one of the following:

Numpad0::WinMaximize A   ; Maximize the active/foreground window.
Numpad0::Send {Numpad0}  ; Make the release of Numpad0 produce a Numpad0 keystroke. See comment below.

Fire on release: The presence of one of the above custom combination hotkeys causes the release of Numpad0 to perform the indicated action, but only if you did not press any other keys while Numpad0 was being held down. : This behaviour can be avoided by applying the to either hotkey.

Modifiers: Unlike a normal hotkey, custom combinations act as though they have the modifier by default. For example, will activate even if Ctrl or Alt is held down when 1 and 2 are pressed, whereas would be activated only by Ctrl+1 and not Ctrl+Alt+1.

For standard modifier keys, normal hotkeys typically work as well or better than «custom» combinations. For example, is recommended over .

Combinations of three or more keys are not supported. Combinations which your keyboard hardware supports can usually be detected by using #If and , but the results may be inconsistent. For example:

; Press AppsKey and Alt in any order, then slash (/).
#if GetKeyState("AppsKey", "P")
Alt & /::MsgBox Hotkey activated.

; If the keys are swapped, Alt must be pressed first (use one at a time):
#if GetKeyState("Alt", "P")
AppsKey & /::MsgBox Hotkey activated.

;  & \::
#if GetKeyState("")
\::MsgBox

Keyboard hook: Custom combinations involving keyboard keys always use the keyboard hook, as do any hotkeys which use the prefix key as a suffix. For example, causes to always use the hook.

Other Features

NumLock, CapsLock, and ScrollLock: These keys may be forced to be «AlwaysOn» or «AlwaysOff». For example: .

Overriding Explorer’s hotkeys: Windows’ built-in hotkeys such as Win+E (#e) and Win+R (#r) can be individually overridden simply by assigning them to an action in the script. See the override page for details.

Substitutes for Alt-Tab: Hotkeys can provide an alternate means of alt-tabbing. For example, the following two hotkeys allow you to alt-tab with your right hand:

RControl & RShift::AltTab  ; Hold down right-control then press right-shift repeatedly to move forward.
RControl & Enter::ShiftAltTab  ; Without even having to release right-control, press Enter to reverse direction.

For more details, see .

Tray Icon

By default, each script adds its own icon to the taskbar notification area (commonly known as the tray).

The tray icon usually looks like this (but the color or letter changes when the script is paused or suspended):

Right-click the tray icon to show the tray menu, which has the following options by default:

  • Open — Open the script’s .
  • Help — Open the AutoHotkey offline help file.
  • Window Spy — Displays various information about a window.
  • Reload This Script — See Reload.
  • Edit This Script — See Edit.
  • Suspend Hotkeys — Suspend or unsuspend hotkeys.
  • Pause Script — Pause or unpause the script.
  • Exit — Exit the script.

By default, double-clicking the tray icon shows the script’s .

The Menu command can be used to customise the tray icon and menu.

The #NoTrayIcon directive can be used to hide the tray icon.

8 — Other Helpful Goodies

We have reached the end of our journey, my good friend. I hope you have learned something. But before we go, here are some other things that I think you should know. Enjoy!

a. The mysterious square brackets

Throughout the documentation, you will see these two symbols ( and ) surrounding code in the yellow syntax box at the top of almost all pages. Anything inside of these brackets are OPTIONAL. Meaning the stuff inside can be left out if you don’t need them. When writing your code, it is very important to NOT type the square brackets in your code.

On the ControlGetText page you will see this:

ControlGetText, OutputVar , Control, WinTitle, WinText, ExcludeTitle, ExcludeText

So you could simply do this if you wanted:

ControlGetText, OutputVar

Or add in some more details:

ControlGetText, OutputVar, Control, WinTitle

What if you wanted to use ExcludeTitle but not fill in WinText or WinTitle? Simple!

ControlGetText, OutputVar, Control,,, ExcludeTitle

Please note that you cannot IGNORE parameters, but you can leave them blank. If you were to ignore , it would look like this and cause issues:

ControlGetText, OutputVar, Control, ExcludeTitle

b. Finding your AHK version

Run this code to see your AHK version:

MsgBox, %A_AhkVersion%

Or look for «AutoHotkey Help File» or «AutoHotkey.chm» in the start menu or your installation directory.

c. Trial and Error

Trial and Error is a very common and effective way of learning. Instead of asking for help on every little thing, sometimes spending some time alone (sometimes hours or days) and trying to get something to work will help you learn faster.

If you try something and it gives you an error, study that error. Then try to fix your code. Then try running it again. If you still get an error, modify your code some more. Keep trying and failing until your code fails no more. You will learn a lot this way by reading the documentation, reading errors and learning what works and what doesn’t. Try, fail, try, fail, try, try, try, fail, fail, succeed!

This is how a lot of «pros» have learned. But don’t be afraid to ask for help, we don’t bite (hard). Learning takes time, the «pros» you encounter did not learn to be masters in just a few hours or days.

«If at first you don’t succeed, try, try, try again.» — Hickson, William E.

d. Indentation

This stuff (indentation) is very important! Your code will run perfectly fine without it, but it will be a major headache for you and other to read your code. Small code (25 lines or less) will probably be fine to read without indentation, but it’ll soon get sloppy. It’s best you learn to indent ASAP. Indentation has no set style, but it’s best to keep everything consistent.

«What is indentation?» you ask? It’s simply spacing to break up your code so you can see what belongs to what. People usually use 3 or 4 spaces or 1 tab per «level».

Not indented:

if (car = "old")
{
MsgBox, The car is really old.
if (wheels = "flat")
{
MsgBox, This car is not safe to drive.
return
}
else
{
MsgBox, Be careful! This old car will be dangerous to drive.
}
}
else
{
MsgBox, My`, what a shiny new vehicle you have there.
}

Indented:

if (car = "old")
{
    MsgBox, The car is really old.
    if (wheels = "flat")
    {
        MsgBox, This car is not safe to drive.
        return
    }
    else
    {
        MsgBox, Be careful! This old car will be dangerous to drive.
    }
}
else
{
    MsgBox, My`, what a shiny new vehicle you have there.
}

See Wikipedia’s Indentation style page for various styles and examples. Choose what you like or learn to indent how you think it’s easiest to read.

e. Asking for Help

Before you ask, try doing some research yourself or try to code it yourself. If that did not yield results that satisfy you, read below.

  • Don’t be afraid to ask for help, even the smartest people ask others for help.
  • Don’t be afraid to show what you tried, even if you think it’s silly.
  • Post anything you have tried.
  • Pretend everyone but you is a doorknob and knows nothing. Give as much information as you can to educate us doorknobs at what you are trying to do. Help us help you.
  • Be patient.
  • Be polite.
  • Be open.
  • Be kind.
  • Enjoy!

If you don’t get an answer right away, wait at least 1 day (24 hours) before asking for more help. We love to help, but we also do this for free on our own time. We might be at work, sleeping, gaming, with family or just too busy to help.

And while you wait for help, you can try learning and doing it yourself. It’s a good feeling, making something yourself without help.

The Top of the Script (the Auto-execute Section)

After the script has been loaded, it begins executing at the top line, continuing until a Return, Exit, hotkey/hotstring label, or the physical end of the script is encountered (whichever comes first). This top portion of the script is referred to as the auto-execute section.

Note: While the script’s first hotkey/hotstring label has the same effect as return, other hotkeys and labels do not.

If the script is not persistent, it will terminate after the auto-execute section has completed. Otherwise, it will stay running in an idle state, responding to events such as hotkeys, hotstrings, , custom menu items, and timers. A script is automatically persistent if it contains hotkeys, hotstrings, OnMessage() or GUI, and in a few other cases. The #Persistent directive can also be used to explicitly make the script persistent.

Every thread launched by a hotkey, hotstring, menu item, , or timer starts off fresh with the default values for the following attributes as set in the auto-execute section. If unset, the standard defaults will apply (as documented on each of the following pages): AutoTrim, CoordMode, Critical, DetectHiddenText, DetectHiddenWindows, FileEncoding, ListLines, SendLevel, SendMode, SetBatchLines, SetControlDelay, SetDefaultMouseSpeed, SetFormat, SetKeyDelay, SetMouseDelay, SetRegView, SetStoreCapsLockMode, SetTitleMatchMode, SetWinDelay, StringCaseSense, and Thread.

If the auto-execute section takes a long time to complete (or never completes), the default values for the above settings will be put into effect after 100 milliseconds. When the auto-execute section finally completes (if ever), the defaults are updated again to be those that were in effect at the end of the auto-execute section. Thus, it’s usually best to make any desired changes to the defaults at the top of scripts that contain hotkeys, hotstrings, timers, or custom menu items. Also note that each thread retains its own collection of the above settings. Changes made to those settings will not affect other threads.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector