Frequently asked questions (faq)
Содержание:
- Returning Values to Caller
- Основные возможности
- Introduction and Simple Examples
- SendPlay [v1.0.43+]
- 1 — The Basics
- Return, Exit, and General Remarks
- Особенности сервиса
- 8 — Other Helpful Goodies
- Send variants
- Что с этим делать
- Script File Codepage [AHK_L 51+]
- Законодательное регулирование
- Mouse Wheel Hotkeys
- Alt-Tab Hotkeys
- Dynamically Calling a Function
- Function Hotkeys [v1.1.20+]
- Как редактировать скрипты AutoHotkey
- Create a Script
- Joystick
Returning Values to Caller
As described in , a function may optionally return a value to its caller.
Test := returnTest() MsgBox % Test returnTest() { return 123 }
If you want to return extra results from a function, you may also use :
returnByRef(A,B,C) MsgBox % A "," B "," C returnByRef(ByRef val1, ByRef val2, ByRef val3) { val1 := "A" val2 := 100 val3 := 1.1 return }
: and can be used to return multiple values or even named values:
Test1 := returnArray1() MsgBox % Test1 "," Test1 Test2 := returnArray2() MsgBox % Test2 "," Test2 Test3 := returnObject() MsgBox % Test3.id "," Test3.val returnArray1() { Test := return Test } returnArray2() { x := 456 y := "EFG" return } returnObject() { Test := {id: 789, val: "HIJ"} return Test }
Основные возможности
- автоматизация различных действий путем эмуляции нажатия определенных клавиш на мыши и клавиатуре;
- написание или запись макросов с использованием рекордера;
- назначение горячих клавиш;
- быстрая расшифровка аббревиатур;
- создание произвольных форм для ввода информации;
- изменение назначения любых клавиш;
- обработка сигналов, переданных внешними устройствами управления;
- преобразование скриптов;
- управление громкостью и другими настройками звуковых карт;
- выполнение мониторинга системы;
- изменение содержимого в буфере обмена;
- отображение на экране надписей и диалоговых окон;
- автоматизация действий в играх;
- любые операции с текстовыми файлами и др.
Плюсы и минусы
Плюсы:
- автоматический запуск практически любых операций на ПК;
- встроенный скриптовый язык;
- переназначение любых клавиш;
- поддержка разных устройств для вывода.
Минусы:
некоторые сложности в освоении.
Похожие программы
Auto-Clicker. Программа для запоминания и последующего воспроизведения всех действий компьютерной мыши. Записанные действия в ней можно повторять произвольное количество раз, настраивая скорость их воспроизведения.
Macro Recorder. Приложение, которое может автоматизировать все рутинные процессы на компьютере. С его помощью можно создавать макросы, которые будут самостоятельно запускать необходимые программы, выполнять клики мышкой, вводить текст и т. д.
Как пользоваться приложением
Для того чтобы с помощью программы назначить автоматическое выполнение какого-либо действия, нужно создать скрипт. Он представляет собой всплывающее окно с пометкой «Я рогалег». С этой целью используем команду MsgBox, которую можно вызвать любым текстом. Надпись и команду необходимо вписать в любой текстовый редактор, так как сама программа как такового отдельного окна не имеет. Далее сохраняем файл, обязательно указав для него расширение «ahk». Скрипт будет выполнен при нажатии на него двойным щелчком.
Выполнение скрипта
При запуске скрипта появится значок «Autohotkey». Нажав на него правой кнопкой, вы сможете выбрать необходимые команды.
Выбор команд
Код, который должен автоматически выполняться при запуске скрипта, помещается вверху файла. Идентификаторы нужно указывать для горячих клавиш.
Рассмотрим, как это действует, на примере назначения автоматического запуска блокнота Notepad++ при нажатии определенных клавиш.
Для начала набираем «#n:: Run notepad++» и сохраняем файл. Дважды щелкаем по нему и набираем команду «Win+n». В области уведомления появится значок, а программа будет запущена при нажатии указанной комбинации клавиш.
В команде значок «#n» определяет кнопки, «::» — разделяет обозначения самих клавиш от команд. Остальные базовые кнопки обозначаются таким образом:
Обозначения кнопок
AutoHotkey поможет легко и быстро выполнять любые операции и действия, которые вам приходится часто производить на своем ПК.
Introduction and Simple Examples
Hotkeys are sometimes referred to as shortcut keys because of their ability to easily trigger an action (such as launching a program or keyboard macro). In the following example, the hotkey Win+N is configured to launch Notepad. The pound sign stands for the Win key, which is known as a modifier:
#n:: Run Notepad return
In the final line above, serves to finish the hotkey. However, if a hotkey needs to execute only a single line, that line can be listed to the right of the double-colon. In other words, the is implicit:
#n::Run Notepad
To use more than one modifier with a hotkey, list them consecutively (the order does not matter). The following example uses to indicate Control+Alt+S:
^!s:: Send Sincerely,{enter}John Smith ; This line sends keystrokes to the active (foremost) window. return
SendPlay [v1.0.43+]
Warning: SendPlay may have no effect at all if UAC is enabled, even if the script is running as an administrator. For more information, refer to the .
SendPlay’s biggest advantage is its ability to «play back» keystrokes and mouse clicks in a broader variety of games than the other modes. For example, a particular game may accept only when they have the .
Of the three sending modes, SendPlay is the most unusual because it does not simulate keystrokes and mouse clicks per se. Instead, it creates a series of events (messages) that flow directly to the active window (similar to ControlSend, but at a lower level). Consequently, SendPlay does not trigger hotkeys or hotstrings.
Like , SendPlay’s keystrokes do not get interspersed with keystrokes typed by the user. Thus, if the user happens to type something during a SendPlay, those keystrokes are postponed until afterward.
Although SendPlay is considerably slower than SendInput, it is usually faster than the traditional mode (even when KeyDelay is -1).
The Win keys (LWin and RWin) are automatically blocked during a SendPlay if the keyboard hook is installed. This prevents the Start Menu from appearing if the user accidentally presses a Win key during the send. By contrast, keys other than LWin and RWin do not need to be blocked because the operating system automatically postpones them until after the SendPlay (via buffering).
SendPlay does not use the standard settings of SetKeyDelay and SetMouseDelay. Instead, it defaults to no delay at all, which can be changed as shown in the following examples:
SetKeyDelay, 0, 10, Play ; Note that both 0 and -1 are the same in SendPlay mode. SetMouseDelay, 10, Play
SendPlay is unable to turn on or off CapsLock, NumLock, or ScrollLock. Similarly, it is unable to change a key’s state as seen by GetKeyState unless the keystrokes are sent to one of the script’s own windows. Even then, any changes to the left/right modifier keys (e.g. RControl) can be detected only via their neutral counterparts (e.g. Control). Also, SendPlay has other limitations described on the .
Unlike and , the user may interrupt a SendPlay by pressing Control+Alt+Del or Control+Escape. When this happens, the remaining keystrokes are not sent but the script continues executing as though the SendPlay had completed normally.
Although SendPlay can send LWin and RWin events, they are sent directly to the active window rather than performing their native operating system function. To work around this, use . For example, would show the Start Menu’s Run dialog.
1 — The Basics
Before we begin our journey, let me give some advice. Throughout this tutorial you will see a lot of text and a lot of code. For optimal learning power, it is advised that you read the text and try the code. Then, study the code. You can copy and paste most examples on this page. If you get confused, try reading the section again.
a. Downloading and installing AutoHotkey
Since you’re viewing this documentation locally, you’ve probably already installed AutoHotkey and can skip to section b.
Before learning to use AutoHotkey (AHK), you will need to download it. After downloading it, you may possibly need to install it. But that depends on the version you want. For this guide we will use the Installer since it is easiest to set up.
Text instructions:
- Go to the AutoHotkey Homepage: https://www.autohotkey.com/
- Click Download: https://www.autohotkey.com/download/ahk-install.exe
- During installation of AutoHotkey, you will be asked to choose from UNICODE or ANSI. In short, you would probably want to choose UNICODE. It has support for non-English letters and numbers (characters). Keep going until you see an Install button.
- Once done, great! Continue on to section b.
For a video instruction, watch
Install and Hello World on YouTube.
b. How to create a script
Once you have AutoHotkey installed, you will probably want it to do stuff. AutoHotkey is not magic, we all wish it was, but it is not. So we will need to tell it what to do. This process is called «Scripting».
Text instructions:
- Right-Click on your desktop.
- Find «New» in the menu.
- Click «AutoHotkey Script» inside the «New» menu.
- Give the script a new name. It must end with a .ahk extension. For example: MyScript.ahk
- Find the newly created file on your desktop and right-click it.
- Click «Edit Script».
- A window should have popped up, probably Notepad. If so, SUCCESS!
So now that you have created a script, we need to add stuff into the file. For a list of all built-in commands, function and variables, see .
Here is a very basic script containing a hotkey which types text using the Send command when the hotkey is pressed:
^j:: Send, My First Script return
We will get more in-depth later on. Until then, here’s an explanation of the above code:
- The first line: is the hotkey. means Ctrl, is the letter J. Anything to the left of are the keys you need to press.
- The second line: is how you send keystrokes. is the command, anything after the comma (,) will be typed.
- The third line: . This will become your best friend. It literally stops code from going any further, to the lines below. This will prevent many issues when you start having a lot of stuff in your scripts.
- Save the File.
- Double-click the file/icon in the desktop to run it. Open notepad or (anything you can type in) and press Ctrl and J.
- Hip Hip Hooray! Your first script is done. Go get some reward snacks then return to reading the rest of this tutorial.
For a video instruction, watch Install and Hello World on YouTube.
c. You cannot merge commands
When you are making your code, you might have the urge to put several commands on the same line or inside of each other, don’t. we’ll talk about why it doesn’t work as you might expect and what you can do instead.
d. How to find the help file on your computer
There are a few ways to do this, I’ll assume you have it installed to the default locations:
Method 1:
- Find the Start menu or Start Orb on your screen, usually in the lower left.
- Click Programs or All Programs.
- Find AutoHotkey in the list.
- You should then see AutoHotkey Help File. Click it.
- Done!
Method 2:
- Go to your desktop.
- Find My Computer or Computer. Open it.
- Go into your harddrive that contains AutoHotkey. Probably C:\ drive.
- Search within all Program Files folders for AutoHotkey.
- Look for AutoHotkey.chm or a file that says AutoHotkey and has a yellow question mark on it.
- Done!
Return, Exit, and General Remarks
If the flow of execution within a function reaches the function’s closing brace prior to encountering a Return, the function ends and returns a blank value (empty string) to its caller. A blank value is also returned whenever the function explicitly omits Return’s parameter.
When a function uses the Exit command to terminate the current thread, its caller does not receive a return value at all. For example, the statement would leave unchanged if exits. The same thing happens if a function causes a runtime error such as running a nonexistent file (when is not in effect).
A function may alter the value of ErrorLevel for the purpose of returning an extra value that is easy to remember.
To call a function with one or more blank values (empty strings), use an empty pair of quotes as in this example: .
Since calling a function does not start a new thread, any changes made by a function to settings such as SendMode and SetTitleMatchMode will go into effect for its caller too.
The caller of a function may pass a nonexistent variable or array element to it, which is useful when the function expects the corresponding parameter to be . For example, calling would create the variable automatically as a or global (depending on whether the caller is inside a function and whether it has the in effect).
When used inside a function, ListVars displays a function’s along with their contents. This can help debug a script.
Особенности сервиса
Перед вами новая эпоха телевиденья в своем лучшем виде. Что же оно предлагает? Список впечатляет. Вот некоторые особенности рассматриваемой системы.
- Любимые телеканалы можно отнести к списку избранных, или закрыть паролем доступ к ним;
- На официальном сайте ottplayer.es есть огромное количество информации, позволяющей работать без помощи мастера или любого другого человека. Все настройки можно совершить самостоятельно, пользуясь только виртуальными подсказками, что состоят из видео и текстового контента;
- Рассматриваемое телевидение может работать не просто на телевизорах, но и на других смарт устройствах, учитывая компьютеры и смартфоны, чтобы получить доступ к своим данным.
https://youtube.com/watch?v=My0tkNu8LZ8
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.
Send variants
Send: By default, Send is synonymous with SendEvent; but it can be made a synonym for SendInput or SendPlay via SendMode.
SendRaw: Similar to Send, except that all characters in Keys are interpreted and sent literally. See for details.
SendInput and SendPlay : SendInput and SendPlay use the same syntax as Send but are generally faster and more reliable. In addition, they buffer any physical keyboard or mouse activity during the send, which prevents the user’s keystrokes from being interspersed with those being sent. SendMode can be used to make Send synonymous with SendInput or SendPlay. For more details about each mode, see and below.
SendEvent : SendEvent sends keystrokes using the same method as the pre-1.0.43 Send command. The rate at which keystrokes are sent is determined by SetKeyDelay.
Что с этим делать
- Поставьте четкие, понятные цели и задачи — зачем вам сейчас понимание ЦА.
- Соберите всю информацию о своей аудитории через статистику сайта, своих сообществ, опросы и анкеты.
- Проведите фокус-группы и интервью, если это возможно.
- Соберите всю информацию о своей ЦА и разбейте её на сегменты с помощью метода 5W или с привязкой к одному из важных для вашего продукта критериев.
- Дождитесь 2-ю часть нашей инструкции =)
В следующей части инструкции мы расскажем:
- как составить портреты клиентов;
- какие психотипы клиентов стоит использовать;
- что такое «лестница узнавания» по Бену Ханту;
- как могут выглядеть портреты клиентов (примеры).
23316
Script File Codepage [AHK_L 51+]
In order for non-ASCII characters to be read correctly from file, the encoding used when the file was saved (typically by the text editor) must match what AutoHotkey uses when it reads the file. If it does not match, characters will be decoded incorrectly. AutoHotkey uses the following rules to decide which encoding to use:
- If the file begins with a UTF-8 or UTF-16 (LE) byte order mark, the appropriate codepage is used and the switch is ignored.
- If the switch is passed on the command-line, codepage n is used. For a list of possible values, see Code Page Identifiers.
Note: The «Default to UTF-8» option in the AutoHotkey installer adds to the command line for all scripts launched via the shell (Explorer).
- In all other cases, the system default ANSI codepage is used.
Note that this applies only to script files loaded by AutoHotkey, not to file I/O within the script itself. FileEncoding controls the default encoding of files read or written by the script, while IniRead and IniWrite always deal in UTF-16 or ANSI.
As all text is converted (where necessary) to the , characters which are invalid or don’t exist in the native codepage are replaced with a placeholder: ANSI ‘?’ or Unicode ‘�’. In Unicode builds, this should only occur if there are encoding errors in the script file or the codepages used to save and load the file don’t match.
RegWrite may be used to set the default for scripts launched from Explorer (e.g. by double-clicking a file):
; Uncomment the appropriate line below or leave them all commented to ; reset to the default of the current build. Modify as necessary: ; codepage := 0 ; System default ANSI codepage ; codepage := 65001 ; UTF-8 ; codepage := 1200 ; UTF-16 ; codepage := 1252 ; ANSI Latin 1; Western European (Windows) if (codepage != "") codepage := " /CP" . codepage cmd="%A_AhkPath%"%codepage% "`%1" `%* key=AutoHotkeyScript\Shell\Open\Command if A_IsAdmin ; Set for all users. RegWrite, REG_SZ, HKCR, %key%,, %cmd% else ; Set for current user only. RegWrite, REG_SZ, HKCU, Software\Classes\%key%,, %cmd%
This assumes AutoHotkey has already been installed. Results may be less than ideal if it has not.
Законодательное регулирование
Mouse Wheel Hotkeys
Hotkeys that fire upon turning the mouse wheel are supported via the key names WheelDown and WheelUp. Here are some examples of mouse wheel hotkeys:
MButton & WheelDown::MsgBox You turned the mouse wheel down while holding down the middle button. ^!WheelUp::MsgBox You rotated the wheel up while holding down Control+Alt.
: WheelLeft and WheelRight are also supported, but have no effect on operating systems older than Windows Vista. Some mice have a single wheel which can be scrolled up and down or tilted left and right. Generally in those cases, WheelLeft or WheelRight signals are sent repeatedly while the wheel is held to one side, to simulate continuous scrolling. This typically causes the hotkeys to execute repeatedly.
: The built-in variable A_EventInfo contains the amount by which the wheel was turned, which is typically 1. However, A_EventInfo can be greater or less than 1 under the following circumstances:
- If the mouse hardware reports distances of less than one notch, A_EventInfo may contain 0;
- If the wheel is being turned quickly (depending on type of mouse), A_EventInfo may be greater than 1. A hotkey like the following can help analyze your mouse: .
Some of the most useful hotkeys for the mouse wheel involve alternate modes of scrolling a window’s text. For example, the following pair of hotkeys scrolls horizontally instead of vertically when you turn the wheel while holding down the left Control key:
~LControl & WheelUp:: ; Scroll left. ControlGetFocus, fcontrol, A Loop 2 ; <-- Increase this value to scroll faster. SendMessage, 0x114, 0, 0, %fcontrol%, A ; 0x114 is WM_HSCROLL and the 0 after it is SB_LINELEFT. return ~LControl & WheelDown:: ; Scroll right. ControlGetFocus, fcontrol, A Loop 2 ; <-- Increase this value to scroll faster. SendMessage, 0x114, 1, 0, %fcontrol%, A ; 0x114 is WM_HSCROLL and the 1 after it is SB_LINERIGHT. return
Finally, since mouse wheel hotkeys generate only down-events (never up-events), they cannot be used as .
Alt-Tab Hotkeys
Each Alt-Tab hotkey must be a combination of two keys, which is typically achieved via the ampersand symbol (&). In the following example, you would hold down the right Alt key and press J or K to navigate the alt-tab menu:
RAlt & j::AltTab RAlt & k::ShiftAltTab
AltTab and ShiftAltTab are two of the special commands that are only recognized when used on the same line as a hotkey. Here is the complete list:
AltTab: If the alt-tab menu is visible, move forward in it. Otherwise, display the menu (only if the hotkey is an «&» combination of two keys; otherwise, it does nothing).
ShiftAltTab: Same as above except move backward in the menu.
AltTabMenu: Show or hide the alt-tab menu.
AltTabAndMenu: If the alt-tab menu is visible, move forward in it. Otherwise, display the menu.
AltTabMenuDismiss: Close the Alt-tab menu.
To illustrate the above, the mouse wheel can be made into an entire substitute for Alt-tab. With the following hotkeys in effect, clicking the middle button displays the menu and turning the wheel navigates through it:
MButton::AltTabMenu WheelDown::AltTab WheelUp::ShiftAltTab
To cancel a hotkey-invoked Alt-tab menu without activating the selected window, use a hotkey such as the following. It might require adjustment depending on: 1) the means by which the alt-tab menu was originally displayed; and 2) whether the script has the keyboard hook installed.
LCtrl & CapsLock::AltTab !MButton:: ; Middle mouse button. The ! prefix makes it fire while the Alt key is down (which it is if the alt-tab menu is visible). if WinExist("ahk_class #32771") ; Indicates that the alt-tab menu is present on the screen. Send !{Escape}{Alt up} return
Currently, all special Alt-tab actions must be assigned directly to a hotkey as in the examples above (i.e. they cannot be used as though they were commands). They are not affected by #IfWin or #If.
Custom alt-tab actions can also be created via hotkeys. In the following example, you would press F1 to display the menu and advance forward in it. Then you would press F2 to activate the selected window (or press Escape to cancel):
*F1::Send {Alt down}{tab} ; Asterisk is required in this case. !F2::Send {Alt up} ; Release the Alt key, which activates the selected window. ~*Escape:: if WinExist("ahk_class #32771") Send {Escape}{Alt up} ; Cancel the menu without activating the selected window. return
Dynamically Calling a Function
: A function (even a ) may be called dynamically via percent signs. For example, would call the function whose name is contained in Var. Similarly, would call Func1() or Func2(), etc., depending on the current value of A_Index.
: Var in can contain a function name or a function object. If the function does not exist, the ‘s __Call meta-function is invoked instead.
If the function cannot be called due to one of the reasons below, the evaluation of the expression containing the call stops silently and prematurely, which may lead to inconsistent results:
- Calling a nonexistent function, which can be avoided by using . Except for , the called function’s must exist explicitly in the script by means such as #Include or a non-dynamic call to a .
- Passing too few parameters, which can be avoided by checking ‘s return value (which is the number of mandatory parameters plus one). : Note that passing too many parameters is tolerated; each extra parameter is fully evaluated (including any calls to functions) and then discarded.
Finally, a dynamic call to a function is slightly slower than a normal call because normal calls are resolved (looked up) before the script begins running.
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
Допустим, вы решили переключить поиск на YouTube. Чтобы отредактировать скрипт AutoHotkey, щелкните его правой кнопкой мыши и выберите Редактировать скрипт, Это откроет скрипт в вашем текстовом редакторе по умолчанию. URL для поиска на YouTube немного отличается.
Сохраните скрипт. Вы можете использовать этот скрипт сразу, не закрывая и не открывая заново скрипт. Вместо этого щелкните правой кнопкой мыши значок в системном трее и выберите Перезагрузить этот скрипт, Скопируйте что-нибудь в буфер обмена и попробуйте!
Это может быть просто самый быстрый из возможных способов поиска на YouTube, который демонстрирует некоторые из лучших трюков с URL-адресами YouTube.
10 хитростей URL YouTube, о которых вы должны знать
10 хитростей URL YouTube, о которых вы должны знатьЛюбите YouTube? Вы можете сделать это еще лучше с помощью этих классных трюков с URL-адресами YouTube, которые позволяют загружать видео, создавать GIF-файлы и многое другое.
Прочитайте больше
!
Create a Script
There are a couple of common ways to create a script file:
- In Notepad (or a of your choice), save a file with the filename extension. On some systems you may need to enclose the name in quotes to ensure the editor does not add another extension (such as .txt).
Be sure to save the file as UTF-8 with BOM if it will contain non-ASCII characters. For details, see the .
- In Explorer, right-click in empty space in the folder where you want to save the script, then select New and AutoHotkey Script. You can then type a name for the script (taking care not to erase the extension if it is visible).
See Scripting Language for details about how to write a script.
Joystick
Joy1 through Joy32: The buttons of the joystick. To help determine the button numbers for your joystick, use this . Note that hotkey prefix symbols such as ^ (control) and + (shift) are not supported (though GetKeyState can be used as a substitute). Also note that the pressing of joystick buttons always «passes through» to the active window if that window is designed to detect the pressing of joystick buttons.
Although the following Joystick control names cannot be used as hotkeys, they can be used with GetKeyState:JoyX, JoyY, and JoyZ: The X (horizontal), Y (vertical), and Z (altitude/depth) axes of the joystick.JoyR: The rudder or 4th axis of the joystick. JoyU and JoyV: The 5th and 6th axes of the joystick. JoyPOV: The point-of-view (hat) control.JoyName: The name of the joystick or its driver. JoyButtons: The number of buttons supported by the joystick (not always accurate). JoyAxes: The number of axes supported by the joystick.JoyInfo: Provides a string consisting of zero or more of the following letters to indicate the joystick’s capabilities: Z (has Z axis), R (has R axis), U (has U axis), V (has V axis), P (has POV control), D (the POV control has a limited number of discrete/distinct settings), C (the POV control is continuous/fine). Example string: ZRUVPD
Multiple Joysticks: If the computer has more than one joystick and you want to use one beyond the first, include the joystick number (max 16) in front of the control name. For example, 2joy1 is the second joystick’s first button.
Note: If you have trouble getting a script to recognize your joystick, one person reported needing to specify a joystick number other than 1 even though only a single joystick was present. It is unclear how this situation arises or whether it is normal, but experimenting with the joystick number in the can help determine if this applies to your system.
See Also:Joystick remapping: methods of sending keystrokes and mouse clicks with a joystick.: using a joystick as a mouse.