Digging Deeper Into AutoHotkey (Part I)

Amazon.com: Digging Deeper into AutoHotkey: Tips, Tricks, and ...


Table of Contens:

Introduction to Even More AutoHotkey Script Writing

“AutoHotkey is more than just a few hotkey substitutions.”
While there are many simple uses for AutoHotkey, it can be so much more as long as you take the right approach to writing your scripts.
In some ways the name AutoHotkey is deceptive. It implies that the scripting language is all about remapping the Windows keyboard to set up macro substitutions. While this capability is certainly part of AutoHotkey, there is so much more that can be done with the free utility. There is enough power in the commands to build complete apps that have little to do with the term "Hotkey." In this book alone there are examples of real-time spelling correction of commonly misspelled words, moving active windows on command, initiating a Google search from any program, quick backup apps, menus to replace the missing Windows 8 Start Menu, a quick reminder pop-up that talks, an app that calculates and displays the ages of kids down to the day, and much more. The wealth of scripts in this book only scratches the surface of what is possible with AutoHotkey.
While the most used AutoHotkey commands and techniques are included in this book, it is not a regurgitation of all the AutoHotkey Commands. In fact, many of the commands don't appear in this book at all. AutoHotkey has much more power than most people will ever use. Only advanced programmers are likely to use AutoHotkey to tweak the Windows Registry or make use of Windows Messages. (While there is a simple use of the AutoHotkey DllCall function included, the topic is not covered in detail.) These more advanced AutoHotkey commands are all readily available on the Web, but their use is beyond the scope of this book. The purpose here is to show you how to do those things with AutoHotkey which will have the most impact when used on your Windows computer while giving you a better understanding of AutoHotkey's potential.
Nor does this book contain everything you need to know about AutoHotkey. Rather it is a continuation of the learning process which started with A Beginner's Guide to AutoHotkey. If you are brand new to AutoHotkey and script writing then you may want to start with that book. If you already know the basics, then you may find this book worthwhile for the additional ideas and techniques it offers. If you're a more experienced programmer, then you probably don't need this book at all since all the commands and an active AutoHotkey forum are readily available on the Web.
The goal of this book is to help the novice and intermediate script writer become more familiar with AutoHotkey and programming. The more someone understands the nuances of a scripting language, the easier it is to write simple applications. While the AutoHotkey Command listing on the Web technically gives you everything that you need to write a script, the commands don't always work the way you may expect. I've tested everything in this book and explain how the scripts actually work (plus I highlight the mistakes that I made when working on them).
Everything in this book builds on previous chapters (and books). Therefore, if you are new to programming, it is useful to start in the beginning and work your way through the process. If you are experienced with other languages, then jumping around for ideas may suit you. Since this is not a reference book, I've indexed the chapters to make it easier to find the discussions of specific AutoHotkey commands and techniques. Plus, each introduction to the sections of the book includes a subindex specifically for the material in that part.
There are a number of AutoHotkey apps offered in this book to help you understand how to write AutoHotkey scripts. Each has specific learning points giving a more in-depth understanding of how AutoHotkey works and what it can do for you. Feel free to modify these apps to suit your own purposes. Although they are all functional on some level, a couple of them (Reminder app and Grandkids app) are not truly completed. Further work on those apps will continue in the coming months which will appear in my weekly AutoHotkey column and in another more advanced book sometime in the future. (In particular, I plan to add multiple and recurring reminders to the Reminder app and more database functions (write, edit, search, sort, etc.) to the GrandKids app.)

What's in this Book

The first part of the book, "A Few Quick Tricks in AutoHotkey and Window Spy," includes a number of tips and short apps for the novice AutoHotkey script writer. Each chapter includes specific AutoHotkey techniques while offering tricks which can immediately be put to use.
Part II, "The Zen of Writing AutoHotkey Scripts," is about the holistic process of script writing while developing an app using an AutoHotkey drop down menu to snap and resize windows on the Windows Desktop. Each AutoHotkey command used is explained in detail. Plus, an app to bring lost windows into view is analyzed.
Not every Windows program has built in backup. In Part III, "AutoHotkey for Quick Backup of Your Work, Anywhere, Anytime!," There are AutoHotkey techniques which can be used to protect your work—even when working on the Web.
Do you use Web browsers to do research? Make the data and URL collection process easier with the ideas found in Part IV, "Collect Data in One Pot." A free Scratchpad app (by another script writer) is discussed for its learning points.
Who needs the Start Menu in Windows 8? Or in Windows 7, or XP, for that matter? In Part V, "Quick Launch Links and Menus," there are two different approaches to creating Start Menu-like pop-ups. I now use my AutoHotkey QuickLinks app which quickly navigates my favorite programs and Web pages. It's easy to set up and modify the QuickLinks code. There are even tips for adding the menu to the Windows Taskbar System Tray.
Microsoft Word has some pretty good autocorrection for commonly misspelled words. Now, with the AutoHotkey scripts found in Part VI, "AutoCorrect for All Windows Apps and AutoUpdating AutoHotkey on Multiple Computers," you can add all the same autocorrection to all of your Windows programs and Web pages. Plus, learn how to automatically update all of your AutoHotkey script on all of your computers with Dropbox.
The Reminder app discussed in Part VII, "Building the Reminder App Step by Step," started as a quick pop-up for an appointment later in the same day. The script writing process added a speaking voice reading the message and ultimately saves the reminder to disk. While the app is not quite finished in this book (when is an app ever finished?), it is certainly functional enough for use.
In the last few chapters of the book, Part VIII, "Introduction to Databases, Calculating Ages, and Formatting Problems," it is demonstrated how an INI file can be used as a database. A comprehensive age calculation function is introduced. The formatting and placement of controls in a GUI object is explained.
This book is not the last AutoHotkey book I will publish. I'm continuing to write a weekly column and am now more active on the AutoHotkey Forum. While each book is a compilation of the earlier columns, I do a great deal of updating, editing and correction before the book is published. If you find any errors in this book, please let me know so I can update and republish this book. I'll make sure you get a new copy. Please use this address: ebooks@computoredge.com

Part I: A Few Quick Tricks in AutoHotkey and Window Spy

“Nine chapters of simple AutoHotkey applications, plus the AutoIt Window Spy utility.”
For the novice there are a number of quick app which make AutoHotkey immediately useful. These tips can be used on their own or in other AutoHotkey scripts. Plus, the AutoIt Window Spy utility is introduced for finding mouse click coordinates and identifying windows and controls by name.
Part I of this book is dedicated to bringing simple quick applications to your Windows computer. There is nothing better for your script writing motivation than immediate success. The tips in the following nine chapters can stand alone or be added to other more involved scripts. Plus, Chapter Ten talks about AutoIt Window Spy which may be the most important utility for writing AutoHotkey scripts.
Find an index to Part I at the end of this chapter listing.
Chapter One: Add Currency Symbols and More to Your Keyboard!
A Windows tip for adding special characters to your editing. . .then make it quicker with AutoHotkey
Bring Pennies (?), British Pounds (?), Euros (Ђ), Degrees (°), Plus or Minus signs (±), and much more to your keyboard with Windows Character Map and single lines of AutoHotkey code.
Chapter Two: Adding Curly Quotes and Brackets to Any Document
This AutoHotkey trick demonstrates how to surround any text anywhere with anything.
Whether quoting from a Web page or adding parenthetical remarks, AutoHotkey makes it easier to surround the text in a document or edit window.
Chapter Three: Tip for Long E-Mail Addresses
There is no need to constantly type those long e-mail addresses.
If you have long e-mail addresses then this AutoHotkey tip will make your life easier.
Chapter Four: Always-on-top Tip
A tip for putting any window always-on-top...and off again.
The one-line AutoHotkey always-on-top script is a must-have for Windows Calculator and Sticky Notes.
Chapter Five: A Tip for Mild Dyslexia, Swapping Letters
Here's a trick for swapping two mistyped letters.
A quick app for swapping two letters could help those of us who make typos.
Chapter Six: Do a Google Search from Any Program!
Do a quick Web search!
This is cool! Here is a short, simple AutoHotkey script that allows you to search the Web in any program or window. Anyone can do it!
Chapter Seven: The Disappearing Taskbar Trick
Even the Windows Taskbar can be put away with the stroke of a key.
While this trick may not be the most useful, it does give insight into how AutoHotkey works.
Chapter Eight: Make the Insert and Caps Lock Keys Useful and the Missing Windows Key Solution
Not all keyboards are alike. Here's how to deal with it.
Whether you're an accountant who wants a tab key closer to the number pad or there's no Windows key on your keyboard, AutoHotkey has a solution.
Chapter Nine: A Simple Way to Automate Any Windows Program with (or without) Mouse Movement
An AutoHotkey script for speeding up any windows program menu action, plus use a hotkey to simulate mouse movement.
Tired of navigating menus just to do something simple? Automate it in any Windows program with a single line AutoHotkey script. Not only can AutoHotkey automate keystrokes, but it can also simulate mouse movement and clicks
Chapter Ten: AutoIt Window Spy for Identifying Window Names and Coordinates
Window Spy is possibly the most important utility to use when writing AutoHotkey scripts.
AutoIt Window Spy will give you everything you need to know about the window's inner workings and hidden mechanisms when writing AutoHotkey scripts.

Part I Index to Chapters

::, hotkey substitution, Chapter Eight
Adding quotes and brackets, Chapter Two
Adding Special Symbols in Windows with Character Map, Chapter One
Adding text together (concatenate), Chapter Five
Always-on-top, Chapter Four
AutoHotkey key, mouse buttons and joystick listChapter Eight
Automating Windows programs, Chapter Nine
Change a keyboard key, Chapter Eight
Click commandChapter Nine
Click coordinates, finding, Chapter Ten
Clipboard, Chapter TwoChapter Five
Control names, finding, Chapter Ten
Disabling keyboard keys, Chapter Eight
Disappearing Taskbar Trick, Chapter Seven
Finding control and button names, Chapter Ten
Finding window names, Chapter Ten
Hotstrings in AutoHotkey sectionChapter Three
Hotstring substitution options (:*:), Chapter Three
Keyboard, change a key, Chapter Eight
Keyboard, disabling a key, Chapter Eight
Keyboard, adding a key (), Chapter Eight
Mouse, simulate, Chapter Nine
Mouse click coordinates, finding, Chapter Ten
Sleep command, Chapter TwoChapter FiveChapter Six
SubStr functionChapter Five
Strings, adding together (concatenate), Chapter Five
Text, adding together (concatenate), Chapter Five
Web search, Chapter Six
Window name, finding, Chapter Ten
Window Spy, Chapter Ten
WinHide, Chapter Seven
WinSet commandChapter Four
WinShow, Chapter Seven

Chapter One: Add Currency Symbols and More to Your Keyboard!

“A Windows tip for adding special characters to your editing. . .and then make it quicker with AutoHotkey.”
Bring Pennies (?), British Pounds (?), Euros (Ђ), Degrees (°), Plus or Minus signs (±), and much more to your keyboard with Windows Character Map and single lines of AutoHotkey code.
"Fred made a 180° turn out the door when he realized the price was ?50 rather than Ђ50." "Wilbur's estimates were accurate to the dollar ±50?."
What makes the statements above interesting in not what they say, but the fact that special characters not typically found on American computer keyboards (?, ?, Ђ, ±, ?) were entered into those statements without any changes to the keyboard setup. Each character was added by a simple, one-line AutoHotkey statement. It's remarkably easy to expand and tailor your keyboard characters to exactly what you want or need. But first you must find the special symbols that suit you.

Adding Special Symbols in Windows with Character Map

Windows has a built-in feature, Character Map, for adding special characters and symbols to any document or text editing window. It is a little cumbersome to use, but includes a vast array of characters which will suit almost any need. With Character Map you can copy the symbols directly to your current work or use the information it provides to add your own hotkey combinations to an AutoHotkey script for easy access whenever you need them.
To open Character Map, run (select Run from Start Menu or +R) charmap. (In Windows Vista and Windows 7, type charmap into the Start Search field and select from the results. In Windows 8 use the Search Screen.) The Character Map window will open (see Figure 1).Figure 1. Windows Character Map offers a wide array of characters for use in Windows programs and editing features. (Four of the symbols used in the examples shown here are circled in red.)
As shown in Figure 1, many of the more common special characters are immediately available. Circled in red are four of those used in the examples here. There are quite a few more on the same screen including Yen (?), copyright (©), and the registered trademark sign (®). Each character can be added directly to editing windows by selecting the symbol and copying it to the Clipboard (double-click the symbol, then click the Copy button), then returning to the editing window and pasting it (CTRL+V) into the desired location.
Clicking on one of the symbols provides additional information (see Figure 2). The Unicode number (hexadecimal) appears in the lower left corner and in a pop-up when you hover over the symbol. The lower right corner shows the keystrokes to directly add the symbol to documents without first copying. (Hold down the ALT key and enter the numbers with the number keypad. When the ALT key is released the symbol will appear.)Figure 2. Additional information about a special character is available by clicking on the symbol.
The Unicode value is important in AutoHotkey since it can be used to create hotkeys to expand the capabilities of your keyboard.
Note: The characters available depend upon the font used and programs supporting that font. While many of the symbols are standard and will work in almost all documents and editing windows, some special characters will require the editing software to support the font and may not be properly saved.
While these first four symbols (see Figure 1) were fairly easy to locate, what about the Euro sign (Ђ)? It's nowhere in sight. To find other symbols, check the "Advanced view" box. Additional options will open including a search field (see Figure 3). If you select Unicode Subrange from the "Group by" menu a window will pop up showing common groupings for symbols. If you select Currency, the window displays a group of available symbols for the selected font. (If you are looking for common fractions, select Number Forms.)Figure 3. The Advanced view of Windows Character Map groups symbols by their use. Select Unicode Subrange from "Group by" and select an option from the Group By window. Availability of specific characters depends upon the font selected.
You can also do a direct search for the symbol by entering the search term into the "Search for" field and clicking Search (see Figure 4).Figure 4. A search for "euro" in the Advanced view of Windows Character Map yields the Euro sign.

AutoHotkey to Make It Simpler

While using the Character Map to insert symbols into documents and editing windows is simple enough, if you regularly need symbols not found on your keyboard, the continual jumping back and forth becomes tedious. This is where simple, one-line hotkeys in an AutoHotkey script come to the rescue. The example characters can be added with code shown in Figure 5.
Note: If you're new to AutoHotkey see our Web page "Installing AutoHotkey and Writing Your First Script" for how to get started.Figure 5. Five lines of AutoHotkey code which create hotkeys for the five symbols ((?, ?, Ђ, ?, and ±).
To add this code to an AutoHotkey script copy-and-paste the following into a script—either new or one of your current scripts:
^+4::SendInput {U+00A2}    ;? Cents
^#4::SendInput {U+00A3}    ;? British Pounds
^#+4::SendInput {U+20AC}   ;Ђ Euros
^+o::SendInput {U+00BA}    ;? Degrees
^+=::SendInput {U+00B1}    ;± Plus or minus

Each line sets up one hotkey for the associated symbol.

How It Works

The hotkeys are assigned by the characters in each line of code which appear before the double colon (::). I used hotkeys which could be associated with the current keyboard layout. Note that all of the currency hotkeys use the number four which is also the key for the dollar sign ($, SHIFT+4). This associates all currencies with the same key. The cents sign (?) is CTRL+SHIFT+4. The British Pound (?) is CTRL++4. The Euro sign (Ђ) is CTRL++SHIFT+4. This is in an effort to make the hotkeys easier to remember.
In the case of the degree symbol (?) I used the letter "o" since it looks like a degree symbol. For the plus or minus sign (±) I use the equal sign (=) since the plus sign was on the same key—close enough. Tip: I usually add the SHIFT key or WIN key () to the hotkey combination since the CTRL alone is often another program or Windows hotkey. For example, CTRL plus the equal sign (= or +) in Web browsers increases the size of the text.
Each line of code sends the assigned character to the active window when the hotkeys are pressed simultaneously. After the double colon (::) the line includes SendInput which is "the same syntax as Send but [is] generally faster and more reliable." Plus, the keyboard activity is buffered while the SendInput is executing, which means (if you're a blazing fast typist) you can keep typing without fear of interference with the AutoHotkey addition from the keyboard.
Notice that I used the Unicode value for each hotkey. While you can usually add the symbol itself directly (i.e. ^#4::SendInput {?}), many of the less used symbols may not save in the scripts. For example, when using Notepad the Won currency would not save directly although I could add it with the Unicode. (How well some of the more obscure characters will react depends upon both the font used and the program supporting the font. Finding these problems requires testing the hotkeys in various programs and editing windows.)

Chapter Two: Adding Curly Quotes and Brackets to Any Document

“This AutoHotkey trick demonstrates how to surround any text anywhere with anything.”
Whether quoting from a Web page or adding parenthetical remarks, AutoHotkey makes it easier to surround the text in a document or edit window.
There are times when writing or editing that quotation marks or parentheses need placing around text. Maybe it is a quote copied directly from another document or a Web page. Possibly an aside must be placed in parentheses. If you're a programmer, square brackets or curly brackets are often required for arrays or expressions. Rather than positioning the cursor at each end and adding the characters individually, with AutoHotkey you can write a script which will surround any selected text with quotes using one hotkey combination. Plus, the same script will automatically add quotes to any text that you have copied from another source when you insert it in your working document.
Figure 1 shows three different examples for adding the quotes, smart quotes, parentheses, or any other enclosing symbols to selected text. Generally, they work by first selecting the target text, then hitting assigned hotkey combination. The text is first copied into the Windows Clipboard, the symbols are added to each end of the Clipboard contents, then pasted back into the document. (In the second case, the contents of the Clipboard are Sent to the document without altering the contents of Clipboard. This is often a preferable method as explained below.)Figure 1. AutoHotkey routines for surrounding text with quotation marks or parentheses.
One of the benefits of any of these routines is their dual nature. If you select text within a working document, the hotkey combination returns text with the surrounding punctuation. However, if you copy (CTRL+C) text from another document or Web page, position the cursor in your editing window without selecting any text, then your copied text is inserted along with the surrounding punctuation. This works because the copy function (CTRL+C) only changes the Clipboard when text is actually selected. Otherwise, the original contents of the Clipboard are used.

Adding Straight Quotes

Placing regular quotations marks (") around text is one of the most common uses of this AutoHotkey substitution. This is done by adding the following routine to an AutoHotkey script:
#Q::             ;Add quotes "text"
Send ^c
Sleep 100
clipboard = "%clipboard%"
Send ^v
return

The hotkeys WIN+Q (+Q) copies (CTRL+C) the selected text to the Windows Clipboard, adds the quotation marks to the text in the Clipboard, then pastes (CTRL+V) the Clipboard contents to the editing window.

How It Works

The first line of code (#Q::) designates WIN+Q as the hotkey. The number sign (#) represents the Windows logo key (). The double colon marks the end of the hotkey combination and the beginning of the routine—in this case beginning on the next line.
The second line of code uses the Send command to copy (CTRL+C) the selected text to the Windows Clipboard. Again, if no text is selected, the routine will use whatever was previously stored in the Clipboard (i.e. copied from a Web page or other source).
The third line uses the Sleep command to briefly pause the routine (1/10 of a second) to ensure the copy command is completed and stored to the Clipboard before continuing. Hint: If you find that you're getting inconsistent results from some of your scripts, it could be due to the script outrunning itself. Often adding a short pause (Sleep) will resolve the problem.
The fourth line of code sets the value of the Clipboard contents (clipboard) to the Clipboard plus the surrounding quotes ("%clipboard%"). The surrounding percent signs (%) evaluate the enclosed variable. In this case all that is needed is the quote character (") on each end.
The fifth line of code uses the Send command to paste (CTRL+V) the Clipboard text (with the quotes) into the editing windows.
The last line of code uses the Return command to mark the end of the routine.

Adding Curly (Smart) Quotes

In the second routine for adding smart quotes the Windows Character Map was used to find the Unicode values for each curly quote (U+201C for left quote mark and U+201D for right quote mark). See Figure 2. (See Chapter One for discussion on how to use Character Map.)Figure 2. Using Windows Character Map to find the Unicode values for smart quotes.
The Unicodes are used for smart quotes primarily because the curly quotes do not appear on most keyboards, plus they do not react the same way in all programs or Web editing. Using the Unicode values adds more consistency when using the hotkeys in various programs.
#+Q::              ;Add smart quotes
Send ^c
Sleep 100
SendInput {U+201C}%clipboard%{U+201D}
return

The other major change from the first routine is replacing both the altering of the Clipboard variable by adding quote marks and sending the paste (CTRL+V) command with a one line SendInput command.
In most cases, this is a more robust routine since it does not need to alter the Clipboard contents and uses the speed and buffering of the SendInput command. If you need to add the text in quotes to more than one location, simply place the cursor and hit the hotkey combination. In the first routine, each time you used the hotkeys, additional quotes would be added to the contents of the Clipboard. Using SendInput inserts the text with the quotes without altering the Clipboard contents.
Note that I simply added the SHIFT key (+) to the hotkey combination from the first routine keeping the letter Q (for quotes).
You could also put the curly quote characters directly into the AutoHotkey script (as shown in Figure 3).Figure 3. Adding curly quote characters directly to the routine. (This form of the script is displayed with an image since the ComputorEdge Web editing program automatically strips out curly quotes replacing them with straight quotes. This eliminates potential compatibility problems with other programs and systems.)

Adding Parentheses

The last routine is identical to the first except that it surrounds the selected text with parentheses rather than quotation marks. The letter P (for parentheses) has been used in the hotkey combination.
#P::             ;Add parentheses (text)
Send ^c
Sleep 100
clipboard = (%clipboard%)
Send ^v
return

Alter any of these routines to add hotkey combinations for curly brackets ({}), square brackets ([]), or any other characters for enclosing text.

Chapter Three: Tip for Long E-Mail Addresses

“There is no need to constantly type those long e-mail addresses.”
If you have long e-mail addresses then this AutoHotkey tip will make your life easier.

A Tip for Super Quick E-mail Address Input

One of the main reasons for using AutoHotkey is hot string macro substitution as found in the AutoCorrection app which can be used in any Windows app or Web editing window. Misspell a word and see instant correction or type a couple of characters and an entire word or phrase appears. This is incredibly simple to implement with AutoHotkey and makes writing and editing on your Windows computer much easier.
However, one problem with the Internet is some e-mail addresses are incredibly long. Considering the number of times it's necessary to use your e-mail address in Web forms and as user names, it would be nice to have it appear with a couple of keystrokes. AutoHotkey replacement has been covered previously by me, but the hotkeys are activated by the following keys: a space, period, comma, or some other type of punctuation. In forms and user names we don't want to add a space or punctuation. AutoHotkey has a solution.
A normal macro substitution code line may look like the following:
::j@::jdunning@computoredge.com

This line of code placed in a text file and activated will display the enter e-mail address whenever "j@" is typed followed by a space or most punctuation. A backspace is required in many user name fields to remove the extra space or character. However, if an asterisk (*) is placed between the first two colons like so:
:*:j@::jdunning@computoredge.com

the e-mail is instantly substituted when the @ character is hit—not requiring nor adding any extra space or punctuation. Be sure to pick hotkey combinations that are not likely to occur in the normal course of your work so you won't be surprised by random e-mail addresses popping up.
There are other special characters which can be added between the first two colons. They can be reviewed in the Hotstrings section of the AutoHotkey site. You can also use the letter O to drop the activating space or character, but you would still be required to type it. This would be used if you wanted to add an ending without needing to backspace. For example:
:O:ct:constitut

would add "constitut" without a space leaving you to add "ion", "ing", "es", "ional" or another ending without backspacing.
For more options check out the Hotstrings section linked above.

Chapter Four: Always-on-Top Window Tip

“A tip for putting any window always-on-top...and off again.”
The one-line AutoHotkey always-on-top script is a must-have for Windows Calculator and Sticky Notes.
The Windows calculator found in Windows 7 and Windows 8 is a much improve program with many new features. My complaint about the app is that there is no option to make the calculator window (or Sticky Notes app window) always-on-top. This tip is a one-line app which toggles any active window always-on-top on and off again.
Once the AutoHotkey always-on-top app is running, the first time you hit the hotkey combination CTRL++F8 the active window is set to always-on-top. Do it again and the mode is disabled. The line of code to include in an AHK file is as follows:
^#F8::WinSet, AlwaysOnTop, toggle, A

^#F8 sets up the combination CTRL++FUNCTION KEY 8 as a hotkey. Whenever that hotkey combination is used the WinSet command is executed using the AlwaysOnTop attribute and Toggle value. The A indicates to use the active (selected) window.
This is about as simple as AutoHotkey gets. I've added this function to my regular AHK file. It is amazingly useful. For example, I work with a Web program I wrote specifically for producing e-books. When creating the index for this book I instantly made two windows on top with CTRL++F8 (the chapter editing window and the index editing window), then dragged keywords between the two without losing view of either. Once you get used to always-on-top, you'll be surprised how often you'll use it.

Chapter Five: A Tip for Mild Dyslexia, Swapping Letters

“Here's a trick for swapping two mistyped letters.”
A quick app for swapping two letters could help those of us who make typos.
I'm a little dyslexic—as I believe many people are without realizing it. When I was in school, I could never copy by hand an entire page of a paper without making a mistake—usually reversing letters. I knew exactly what I wanted to write, but was constantly amazed (and frustrated) when I would reverse letters right before my eyes. I have the same problem when typing, but at least with computers it's fairly easy to make corrections. I use the AutoHotkey AutoCorrection which catches many of my mistakes. However, there are still combinations that I need to correct.
This simple AutoHotkey script is a quick fix for those times when two letters are accidentally reversed. Once the script is activated, highlight the reversed letters and use the ALT+R hotkey combination. For example, if you accidentally type "tset" highlight the "se" then hit ALT+R. The two letters are swapped and the corrected word "test" remains. This will work in any Windows program or Web editing field.
To implement this AutoHotkey feature, either create a new AutoHotkey file (.ahk) or add the following to another AutoHotkey file. (I added it to my AutoCorrection file.):
!R::
SendInput, ^c
Sleep, 100
Clipboard := SubStr(Clipboard,2,1) . SubStr(Clipboard,1,1)
SendInput, ^V
Return

The first line of code (!R::) establishes the hotkey combination ALT+R. The exclamation point (!) represents the ALT key. The double colon (::) marks the end of the hotkey combination and the beginning of the routine. The routine includes all the lines up to the "Return" in the last line which marks the end of the routine.
The SendInput command in the second and fifth lines is used to "send" a command to the computer. In this case, "^c" is CTRL+C, the standard Windows command for copying to the Windows Clipboard. The two characters previously highlighted are copied to the Clipboard.
The Sleep command (Sleep, 100) on the third line of code makes the routine pause for one-tenth of a second to ensure that the copy in the previous line is completed before moving on.
The work is done in the fourth line of code using the SubStr function. The SubStr function is used to parse a text string—in this case, the contents of the Clipboard. The first SubStr function (SubStr(Clipboard,2,1)) grabs one character (represented by the number 1) starting with the second character (represented by the number 2). The second SubStr function (SubStr(Clipboard,1,1)) grabs one character (represented by the number 1) starting with the first character (represented by the number 1).
By reversing the order of the two functions and adding them together with the concatenate operator (the period "." between the two functions), the Clipboard is replaced with the reverse order of the two characters originally highlighted.
The last line of code before the "Return" uses the SendInput command to paste (^V represents CTRL+V) the reversed letters in the original locations of the text.
Whether it is easier to highlight the recalcitrant letters and hit ALT+R or merely type the letters in the correct order is questionable. However, this is a demonstration of a simple use of a built-in function.

Chapter Six: Do a Google Search from Any Program!

“Do a quick Web search!”
This is cool! Here is a short, simple AutoHotkey script that allows you to search the Web from any program or window. Anyone can do it!
Let's take a look at the problem of searching the Web for quick answers based upon text selected on your computer screen—regardless of the program you're using. When running almost any Web browser, it is easy to highlight text, right-click, and then search the Web for that text with your default search engine (see Figure 1). Another browser tab opens immediately executing the search. However, what if you're using a word processor, Windows Mail, Adobe Reader, Notepad, Windows Help, or any one of a number of programs? A right-click isn't going to do the job.Figure 1. Select text and right-click in Google Chrome to search the Web for the selected words.
Of course you can always select text from any window, copy it (CTRL+C), open your browser, paste (CTRL+V) the text into the search field, and then launch the search. Or you can create a simple AutoHotkey combination to launch your search for the selected without leaving the window (see Figure 2).Figure 2. An example of an AutoHotkey script for searching the Web for selected text when in any program or window.
To add the code in Figure 2 to an AHK file, copy-and-paste the following:
^+F::
    Send, ^c
    Sleep 100
    Run, http://www.google.com/search?q=%clipboard%
    Return

How It Works

The above routine works by first copying the selected text to the Windows Clipboard. (To select text, click and hold down the left mouse button at the beginning of the text and drag the mouse over the text until the desired portion is highlighted, then release the left mouse button.) The AutoHotkey Run command is used to launch the default browser, opening a new window using Google to search for the contents of the Windows Clipboard.
The first line of code (^+F::) creates the hotkey combination CTRL+SHIFT+F. I used the letter F as the final key because CTRL+F is commonly used for searches. This makes the hotkey a little easier to remember. However, I added the SHIFT key to prevent interference with that popular program hotkey. When deciding upon which hotkeys to create, it is a good idea to add extra keys (in this case the SHIFT key) to prevent conflicts with regular program or Windows hotkeys. Before activating any hotkeys, test the new combination for conflicts within the programs where you're most likely to use them.
The double colon (::) in that same first line of code marks the end of the hotkey combination and the beginning of the action routine.
The second line of code (Send, ^c) uses the AutoHotkey Send command to copy (CTRL+C) the selected text to the Windows Clipboard. The Send command is simulating the same CTRL+C that is used when manually saving a selection to the Clipboard. The value of the Clipboard is always available in a standard AutoHotkey variable called clipboard.
The third line of code (Sleep 100) pauses the routine for 100 microseconds. This is to prevent the execution of the routine from outrunning the process of saving to the Clipboard. If there is no pause, there is a good chance that the new Clipboard value will not yet be available for the search.
The fourth line of code (Run, http://www.google.com/search?q=%clipboard%) is the heart of the routine. The AutoHotkey Run command launches the default browser and executes a Google search for the value of the variable clipboard. When the Run command sees "http://" it launches the default browser and opens the URL (in this case www.google.com/search). The contents of the Windows Clipboard is added to the URL by returning the value of clipboard (?q=%clipboard%). In this line of code, surrounding the variable clipboard with the percent signs (%) tells AutoHotkey to use the contents of the Windows Clipboard.
The last line (Return) simply closes the routine and ends execution.
Once the AutoHotkey script is saved and activated, the hotkey sits ready to launch a search whenever you press CTRL+SHIFT+F simultaneously. For example, if you're using Windows Help and you're curious about searching for more Web information, highlight the target text, then use the hotkey combination (see Figure 3).Figure 3. With the new AutoHotkey script for searching the Web you can even select text in Windows Help, then hit the hotkeys.
Next, press CTRL+SHIFT+F at the same time. Your default browser will open Google search with your selected text as the search terms (see Figure 4).Figure 4. The AutoHotkey routine opens the default browser and runs a Google search with the selected text from another open program or window.
Once you have a universal search hotkey combination, you might be surprised how much you use it.

Chapter Seven: The Disappearing Taskbar Trick

“Even the Windows Taskbar can be put away with the stroke of a key.”
While this trick may not be the most useful, it does give insight into how AutoHotkey works.

Plus a Disappearing Taskbar Trick

I'm not sure about the usefulness of this next Taskbar trick. What it does is remove the Taskbar (with the exception of the Start Menu button) from the screen. One instance where this technique might be useful is when the Taskbar is in Auto-hide mode. If there is a control in a window at the bottom of the screen, it's annoying to go to the control only to have the Taskbar pop up and hide it. With this hotkey combination activated with WinHide in AutoHotkey, you can temporarily remove the Taskbar.Figure 1. The normal Windows Desktop displays the Taskbar.
If you want to find a window's title and class for use in this type of app, then the AutoIt Window Spy, Chapter Ten, will do the trick. Merely load Window Spy by right-clicking on the System Tray AutoHotkey icon (green square with white H inside) of any running AHK script and select Window Spy (or load it from AutoHotkey program group). The Windows Taskbar does not have a title, but it does have an AutoHotkey class (ahk_class Shell_TrayWnd). Of course, once you activate this script, you will no longer be able to see the System Tray.
The following is the code for hiding the Windows Taskbar:
^#!H::WinHide ahk_class Shell_TrayWnd

Once activated, hold down CTRL+WIN()*ALT+H. The Taskbar will disappear (as shown in Figure 4).Figure 2. Windows Desktop with the Taskbar removed the bottom of the screen.
It's important to activate a second hotkey combination to restore (WinShow) the Taskbar. Otherwise, it can become a hassle to get it back:
^#!T::WinShow ahk_class Shell_TrayWnd

Hold down CTRL+WIN()*ALT+T to bring back the Windows Taskbar. If you inadvertently forget to include a WinShow command for restoring the Taskbar, you can get the Taskbar back by opening Task Manager (CTRL+SHIFT+ESC) and ending all instances of explorer.exe in the Processes tab (select and click End Process), then move to the Applications tab and start a new instance of explorer.exe with the "New Task..." button.

Chapter Eight: Make the Insert and Caps Lock Keys Useful and the Missing Windows Key Solution

“Not all keyboards are alike. Here's how to deal with it.”
Whether you're an accountant who wants a tab key closer to the number pad or there's no Windows key on your keyboard, AutoHotkey has a solution.
A question from a ComputorEdge reader:
Can a keyboard button be changed to something other than what is indicated on it?
I use the numerical keypad a lot, and tab between boxes to make my entries. Rather than go all the way to the tab button on the left, can a button next to the number keypad, like the + or Insert button, be changed to a tab?
That's an excellent question. I can see how someone who makes great use of the numeric keypad would want to have other important keys nearby. Then you can really fly just like those payroll clerks on the old mechanical calculators. I like the idea of changing the INSERT key into a TAB key. The INSERT toggle key is pretty much a waste of space on my keyboard.
There are a number of ways to remap Windows keyboard keys. Some of the early ways involved Windows Registry hacks. There is a program which makes the Registry changes a little easier called Sharpkeys. The program looks to be about six years old and I've never used it, but it should work with Windows 7 (I'm guessing). This is yet another problem which can be quickly solved with AutoHotkey.
In AutoHotkey saving the characters Ins::tab to a simple text file and activating it with the main program will turn the INSERT key in a TAB key. Done! The Ins designated the INSERT key as the hotkey. The double colon (::) marks the beginning of the action code. The tab tells the computer to tab every time the INSERT key is hit.
If you want the function key F11 to tab:
F11::tab
If you want the plus sign to tab:
=::tab
(The equals sign is the same as the plus key for hotkey purposes. Using + as part of a hotkey would actually represent the SHIFT key. I wouldn't recommend this one since both = and + would become a TAB key, although it would not affect the + on the numeric keypad—NumpadAdd.)
For other alternatives, see the AutoHotkey key list.

A Simple Trick for Making Better Use of the Caps Lock Key

If you're like me, the caps lock key is an annoyance. I occasionally hit it when I'm aiming for the left shift key. When I look up, I've thrown a bunch of capital letters up onto the screen. (Not that many because I don't type that fast.) In any case, I have little use for the caps lock key. I could disable it with AutoHotkey (Capslock::), but why not make better use of it? In this case, I turn the caps lock key into a hotkey for opening the Windows Calculator app. All that's needed is one short line of code:
Capslock::Run, calc.exe

Add this line to any new or used AutoHotkey script, run with AutoHotkey or compile it and run on any Windows computer, and your caps lock key become the calculator key. Anytime you hit caps lock (even accidentally), the Windows Calculator will pop-up.

No Windows Key on My Keyboard

Another question about a missing Windows  key:
My PC has no Windows key. Is there another key combination that substitutes for it?
You can add a  key to your keyboard by using AutoHotkey to convert one of your less needed keys such as Caps Lock into the Windows key (). Add the line Capslock::lwin to an AHK text file (maybe winkey.ahk) and either run it with AutoHotkey or compile it to an EXE file. See "List of Keys, Mouse Buttons, and Joystick Controls" for a list of possible keys and the AutoHotkey names. You can then add the file (or a shortcut to the file) to your Start folder (Run => shell:start to open your Start folder).

Changing the Hotkey Combinations in Scripts

If you find a script that uses  and there is no Windows  key on your keyboard (and you don't want to add one), then it's merely a matter of locating the key combination in the script, changing it to what is on your keyboard, and running the AHK file (if AutoHotkey is installed) or recompiling it to an EXE file (to run on any Windows computer). The activation hotkeys include a double colon after the hotkeys, in this case:
^#R::    ;CTRL+WIN+R for the Reminder script

found at the beginning of the Reminder.ahk script (Chapter Twenty-six) and
#z::Menu, QuickLinks, Show    ;WIN+Z for the QuickLinks script
!,::Menu, QuickLinks, Show    ;ALT+Comma for the QuickLinks script

found at the end of the QuickLinks.ahk script (Chapter Twenty).
The Windows  key is represented by the # sign. Substitute an alternative symbol from the AutoHotkey list. For example "^" represents the CNTL key, "!" is the ALT key, and "+" is the SHIFT key. Save and rerun the script (or recompile and reload the EXE file) for the changes to take effect.

Chapter Nine: A Simple Way to Automate Any Windows Program with (or without) Mouse Movement

“An AutoHotkey script for speeding up any Windows program menu action, plus use a hotkey to simulate mouse movement.”
Tired of navigating menus just to do something simple? Automate it in any Windows program with a single line AutoHotkey script. Not only can AutoHotkey automate keystrokes, but it can also simulate mouse movement and clicks.

Simple, Powerful Automation for Windows Programs

Most programs have multiple ways to activate the various features. Generally, everything can be done with a few mouse clicks. As an alternative, menus often contain hotkeys which enable the use of the keyboard without the mouse. Yet either one of these methods can become tedious whether it's multiple clicks of the mouse or a series of keyboard strokes. Wouldn't it be nice to include those strokes in a one key macro? Programs such as Microsoft Word have a macro capability for recording and replaying actions. (A macro is a series of computer operations recorded and saved for later quick reuse.) But if you want to create and use macros in any of your Windows programs then AutoHotkey is the answer.
For example, when my spouse and I are on Skype with the grand kids, I like to capture video images of the kids while talking to them (see Figure 1).Figure 1. A video image captured during a Skype session.
To snap an image I open the Call menu with a mouse click, hover over Video, then click Video Snapshot (see Figure 2). Normally, this would not be a big deal except that I'm sharing the space with their grandmother and it's not always easy to get to the mouse. Plus, by the time I snap the image the kids have completely changed their spontaneous pose. They tend to be constantly on the move.Figure 2. The Call menu in Skype allows the capture of video images with the mouse.
For many Windows programs, including Skype, the menus can be accessed via the keyboard with a press of the ALT key. When the ALT key is hit, the menu is selected and the cursors may be used to navigate the menus with the ENTER key for making selections. In addition, the menu has hotkeys (noted by the underlined letters in the menu item, see Figure 3) which are keyboard shortcuts.Figure 3. Keyboard shortcuts highlighted with the underlined letters help to quickly navigate a menu.
Even using the keyboard hotkeys shown in Figure 3 (ALT, a, d, and v) is not easy when reaching across the desk during a video call session. The solution is to add only one line of code to an AutoHotkey script:
Ins::SendInput {alt}adv

This line of AutoHotkey code turns the useless INSERT key into a Skype hotkey for snapping images. It's fast enough to actually capture an expression which may only last a couple of seconds. No more fumbling with the mouse or keyboard combinations.
The Ins in the code designates the INSERT key as the hotkey. The action follows the double colon, ::, and includes the pressing of the ALT key, {alt}, followed by the three hotkeys, ad, and v.
You could also use the exclamation point which represents the ALT key in AutoHotkey rather than alt in curly brackets,
Ins::SendInput !adv
but this technically instructs the ALT key be used in conjunction with the key following it (i.e. ALT+a simultaneously). This works in the example, but there may be some programs which require separate pressing of the two keys. Also, another quirk of using the exclamation point is that !A (with a capital A) would actually represent ALT+SHIFT+A, which may be a problem in some situations.
The other characters which affect the following letter when using the SEND or SENDINPUT command are ^ for CTRL, # for the Windows key (), and + for the SHIFT key.

Using Mouse Simulations

Above a simple AutoHotkey technique for automating many program menu systems is demonstrated. The method uses the INSERT key as a hotkey and sends the underlined menu hotkeys to the program for instant execution. This works great as long as the program has the underlined hotkeys or another way to identify the menus or buttons. But what if there are no hotkeys to use? This next AutoHotkey technique clicks on the location of the items simulating the mouse action whether in a button on a Web page or a link in a program.
AutoHotkey has a cleverly named Click command which simulates the action of the mouse. It is simple to use. All that's needed is the location of the menu item or button in x,y coordinates from the upper left-hand corner of the active program window as shown in Figure 4.Figure 4. The AutoHotkey Click command uses the coordinates (x,y format) of the menu items to simulate the action of the mouse.
The mouse Click code for implementing the example for setting up a hotkey for capturing images of a Skype video call is as follows:
Ins::
  Click 131,38
  Click 171,320
  Click 410,353
Return

The Click command uses the coordinates in the program window for the target menu items. The coordinates need not be exact as long as they fall within the menu item hot area and are relative to the upper left-hand corner of the program window. The coordinates can be obtained from the AutoIt Window Spy program (discussed in Chapter Ten).
The first line of code sets up the INSERT key (Ins) as the hotkey to execute the remainder of the code. The double colon (::) marks the end of the hotkey combination and the beginning of the routine. The following line (Click 131,38) simulates moving the cursor to the 131 pixels from the left and 38 pixels from the top of the active window and clicking the left mouse button. (The Skype window must be the active window for this script to work properly.) The next two lines have the same function for the next two Skype menu items ultimately taking a Video Snapshot. The Return ends the routine.
It's a simple routine. The only problem is determining the right x,y coordinates. For that we turn to AutoIt Window Spy which is installed with the AutoHotkey package.

Chapter Ten: AutoIt Window Spy for Identify Window Names and Coordinates

“Window Spy is possibly the most important utility to use when writing AutoHotkey scripts.”
AutoIt Window Spy will give you everything you need to know about the window's inner workings and hidden mechanisms you need to know when writing AutoHotkey scripts.

AutoIt Window Spy

Window Spy is a utility program from the Windows utility software AutoIt, a close relative of AutoHotkey. When loaded, Window Spy provides the information needed to automate your Windows computing. (AutoIt has a more recent version of Window Spy called AutoIt v3 Window Info. It is included with the full installation of AutoIt—which is also free.) Of particular note in Window Spy are the window title and class, plus the coordinates of the cursor—both on the main screen and within the window (see Figure 1).Figure 1. When hovering the cursor over an area of the active window, Window Spy shows the current x,y coordinates of the cursor location.
While you can load Window Spy from the AutoHotkey program folder, one of the easiest ways to open it is by right-clicking on the System Tray icon of a currently running AHK script and selecting it from the pop-up menu. The AutoHotkey icon is the green square with a white H inside. The System Tray is on the right side of the Windows Taskbar.
To get the proper x,y coordinates, hover the cursor over the target item. Record the "In Active Window" values. While the numbers are exact, there are many sets which will do the job. As long as they fall within the item's hot area, they can be used. If you prefer to copy-and-paste the values, use the SHIFT+ALT+TAB key combination to freeze the Window Spy display. Then highlight and copy the coordinates (see Figure 2).Figure 2. Freeze the Window Spy display with the SHIFT+ALT+TAB key combination.
In other applications, it may be important to identify a GUI control for later use. For example, in the Scratchpad app. discussed in Chapter Eighteen, we used the name of a control to target the instant paste routine. Both the name of the window and the edit field were required. By running Window Spy both pieces of information were immediately apparent (see Figure 3).Figure 3. To ensure that the copied text was inserted in the proper AutoHotkey GUI edit control in the Scratchpad app, Window Spy was used to identify the control name (Edit2).
Many AutoHotkey scripts don't require the identification of the window title, windows class, or cursor position, but for those that do Window Spy is the immediate answer.

Part II: The Zen of Writing AutoHotkey Scripts

“AutoHotkey script writing is a process which does not necessarily go in a straight line.”
This section of Digging Deeper into AutoHotkey has a two-part purpose. The first is to show new script writers how the process really works. If there are programmers who get it right the first time, I don't know any of them. The second part acquaints you with how AutoHotkey moves, positions and resizes windows, plus a script for finding hidden (off the screen) windows.
To be a code writer you need the proper attitude. The average person doesn't know that programming is as creative a process as any of the arts and more inventive than most technical disciplines. There are many ways to get the job done. It's just that some solutions are more elegant than others. The object is to travel the path that will attain that goal. There may be many curves and a few dead-ends, but there is always a way to get there. The novice programmer needs to be aware of the frustrations associated with writing a script and develop the proper mindset for success. When armed with the knowledge and confidence to undertake the journey, the ultimate result is never in doubt. This is the Zen of writing scripts.
In these three chapters, we follow my circuitous course for writing an AutoHotkey script that resizes and positions windows. Since I was learning the commands as I went along, there were errors that came from misunderstanding the language. This is normal when first learning any language. Eventually, when a person becomes fluent with the syntax and capabilities of the code, the script writing becomes easier and more natural.
Chapter Eleven: The Zen of the Script Writing Process (Part 1): Snapping Windows
Writing AutoHotkey scripts that work...eventually! Moving, positioning and resizing windows in Windows.
Programming is a process of trial and error. By doing the work one piece at a time, anyone can successfully write a script. In this first part a script for window resizing and moving is studied.
Chapter Twelve: The Zen of the Script Writing Process (Part 2): Snapping Windows
Writing AutoHotkey Scripts that Work...Eventually!
Jack continues writing an AutoHotkey script for moving and sizing windows by learning the Windows screen coordinate system and adding the action.
Chapter Thirteen: Finding Lost Windows with AutoHotkey
The Answer to a Question about Bringing Back a Lost Window with AutoHotkey
While it may be rare that an open window can't be found, there are ways in AutoHotkey to locate and move all open windows.

Part II Index to Chapters

%, expression evaluation with single %, Chapter Thirteen
%, variable value (percent signs %), Chapter TwelveChapter Thirteen
Active window, Chapter Twelve
Ahk_class Shell_TrayWnd, Chapter Twelve
Array index (A_Index), Chapter Thirteen
Array variable, Chapter Thirteen
Coordinate system (x,y), screen and window location, Chapter Twelve
Concatenating (adding) strings (text), Chapter Thirteen
Concatenating, self-concatenating operator (.=), Chapter Thirteen
Debugging, MsgBox command for, Chapter Eleven
Dropdown menu, Chapter Eleven
DropDownList, Chapter ElevenChapter Thirteen
Formatting, GUI, Chapter Eleven
List open windows (WinGet, OpenWindow, List), Chapter Thirteen
Loop commandChapter Thirteen
Menu, selection, Chapter Eleven
MouseGetPosChapter Twelve
Moving windows, Chapter Eleven
MsgBox, Chapter Thirteen
MsgBox command for debugging, Chapter ElevenChapter Thirteen
Open windows, List (WinGet), Chapter Thirteen
Program Manager (Windows Desktop), Chapter Twelve
"Reload This Scrip", Chapter Eleven
Resizing, windows, Chapter Eleven
Screen and window location system, (coordinates x,y), Chapter Twelve
Selection menu, Chapter Eleven
Shell_TrayWnd (ahk_class), Chapter Twelve
Variable, array, Chapter Thirteen
Variable value (percent signs %%), Chapter Twelve

Chapter Eleven: The Zen of the Script Writing Process (Part 1): Snapping Windows

“Writing AutoHotkey scripts that work...eventually! Moving, positioning and resizing windows in Windows.”
Programming is a process of trial and error. By doing the work one piece at a time, anyone can successfully write a script. In this first part a script for window resizing and moving is studied.
If you've ever written a short program script, only to give up when you couldn't get it working, you will want to read these two chapters on the "Zen of Script Writing." While some people may make it look easy, the reality is that writing a program (even short scripts) is a methodical process requiring many baby steps. There are inevitable errors and direction changes occurring at each step which must be corrected one at a time. Even super programmers suffer through this trial and error process. Don't give up. It's normal.
When things go wrong—which is almost always—writing program scripts is frustrating. Non-programmers look at a long set of code lines and wonder how anyone could ever figured it out. People think that expert software coders just sit down and whip out a new application with thousands of lines of code in an afternoon. That's not what happens. It is rare that any routine runs cleanly the first time. That's why programmers build applications one brick at a time. There may be some people who sit down and write a complete program which runs the first time with no errors, but I'm not one of them. Whenever things look even mildly complicated, I take a systematic approach to programming which allows me to test as I go (success!), eventually cobbling together the working pieces in a logical sequence. Sometimes I just make an error in the syntax of the script. Other times I don't have a proper understanding of how the language actually works—in this case it would be the AutoHotkey commands. I don't try to hide my mistakes in this book, but rather explain them so you can get the same understanding of the process and the commands. I don't explain all my mistakes because that would make the book too long.
For me, learning a computer language is a journey. As I travel down the path I become familiar with the signs and landscape. I learn the nuances of each command and become comfortable with its use. The language slowly becomes a part of me. I will even dream about writing scripts at night. It easily equates with enlightenment as I envision more possibilities. Patience and clarity are the keys to understanding. Sometimes the path is obscure and tedious and it is not until I get to the end that I truly understand the problem—as was the case when I wrote the function for age calculation (Chapter Thirty-four). I started out almost blind patiently plodding along, overcoming one obstacle after another until—at the end—I was able to completely rewrite the age function with a final clarity and comprehension. I didn't truly understand the problem until I had completed the task. There is truly a Zen to learning AutoHotkey.
Not all scripting problems are as difficult as age calculation. In fact most scripts are relatively straight forward. Writing code is like solving a puzzle. While it great to get the final solution, you know that half the fun was the process of figuring out how to get there. Don't put pressure on yourself to finish too quickly—enjoy the trip. At the end you will need to be at peace with your accomplishments because there won't be many who will appreciate your feat. If you find someone who truly understands what you've done, then you have a relationship that you can treasure—for that person also understands the Zen of programming.

A Trip down the Path

Normally in this book, I present the finished code for a new script and explain how the code works. However, this time I show the programming path I suffered through as the script was written and debugged. This approach to introducing a new AutoHotkey script serves two purposes. The first is to explain how the code works and what's needed to get a functional script. The second is to show how programming really gets done and the techniques that make a script run—even if it eventually turns into a long complex application. No application is too difficult if you approach it properly.

Replacing Windows Aero Snap or AquaSnap

Windows Aero Snap and the AquaSnap utility allow the resizing and placement of windows on the Windows Desktop by dragging the windows to the appropriate edge of the computer screen. It is convenient for viewing multiple windows simultaneously and works pretty well. But what if you want to just tell the window where to go rather than dragging windows all over the screen? With AutoHotkey you could set up a hotkey combination for each location on the screen (top half, bottom half, left half, right half, upper left corner, upper right corner, bottom right corner, and bottom left corner), however that would take a lot of hotkey combinations which could be difficult to remember. Perhaps the windows can be moved by making a selection from a dropdown menu which opens with just one hotkey combination (see Figure 1).Figure 1. An AutoHotkey combination opens a dropdown menu for repositioning a window.
When "Top Right Corner" is selected from the dropdown menu the last active window is moved to the top right corner of the computer screen (see Figure 2).Figure 2. When "Top Right Corner" is selected from the dropdown menu the last active window is moved to the top right corner of the computer screen.
While the routine that creates this dropdown menu and moves the window is not super complicated, I made a number of mistakes while writing it. This is normal for any programming. If you're new to programming, you may be tempted to write the entire script all at once, then start debugging it. But, unless a script is only a few lines long, it is best to break it down into manageable pieces.
It is also common to copy another similar script, then make modification for the new script. There is nothing wrong with this approach as long as the changes are minor. I do it all the time. The problem comes in when there are significant differences in the planned results. The original copy's script could mislead you and may actually get in the way of writing a clean solution.
For example, with this window moving routine I originally copied an example which included a function to do the final window resizing and movement. Functions are a good way of repeating similar actions without adding almost identical code multiple times. However, when I was close to the end of the process, I realized that the function actually added unnecessary complications and quite a few more lines of code. If, rather than copying previously written code, I had started from scratch (as is shown here), I would have saved myself time and never introduced the function in the first place. (Sometimes you don't know where you're going until after you get there.)

The Script Writing Process

The first step is to break the end result into basic functional units. In this case, the first result we want is to make a dropdown menu appear on the screen. Next we want a selection from the dropdown menu to initiate an appropriate action. Lastly we want build the corresponding action into the script. The steps I conceived were as follows:
1. Create a dropdown menu.
2. Initiate action from a dropdown selection.
3. Make each possible selection work.
There is nothing sacred about this breakdown. It is merely a way to cope with the problem without trying to do everything at once. If the problem were more involved (building the ComputorEdge Web editing system), I would do a flow chart of the pieces (data files, actions and functions). But for most AutoHotkey scripts, a conceptual breakdown is enough. I probably wouldn't even write it down. It is more about the process than the steps. You could start with writing the window movement routines first, then add the dropdown menu. I like to start with the interface (in this case the dropdown menu), then add the features.

Creating the Dropdown Menu

Making a dropdown menu appear on your screen is relatively simple. You use the GUI (Graphic User Interface) command to ADD elements, and SHOW the graphic. Remember, all I want to do at this point is make something appear on the screen. I added the following code to a new AutoHotkey script:
^#M::
Gui, Add, DropDownList, , Select Position on the Screen||Right Half of Screen
    |Left Half of Screen|Top Half of Screen|Bottom Half of Screen|
Gui, Show,  , Move Window
Return
(Note that some of the selections in the DropDownList are continued on the next line for better display on this page. As long as each following line is preceded by the vertical delimiter "|" it will be treated as a continuation of the previous line.)
I've selected the hotkey combination CTRL++M (^#M before the double colon on the first line) to activate the routine. Even if I don't plan to use the hotkeys when the script is completed, setting it up will make testing easier during the coding process.
The ADD command puts in the DropDownList with the menu items listed at the right. Each item is separated with the vertical line character (|). To make the menu default to a particular value on the list, place a double vertical line (||) at the end of the item. The dropdown list will initially appear with a blank entry if no default is marked.
The GUI, SHOW command activates the dropdown list. Without it the menu will not appear when the hotkey combination is pressed.
After saving the script, I right-click on the file name and select Run Script (See Figure 3 (top)). The little green icon appears in the System Tray on the right side of the Windows Taskbar. In most future iterations to test the latest version, I will save the file again and right-click that System Tray icon selecting Reload This Script (see Figure 3 (bottom left)).Figure 3. Right-click on the saved .AHK file name and select Run Script to activate (top). Right-click on the AutoHotkey System Tray icon to Reload This Script (bottom left). The activated AutoHotkey dropdown menu shows options when clicked on (bottom right).
Note: Incremental testing of a script is important. You need to know that your current code is working before moving on to the next step. The combination of saving the current script, then reloading from the system tray is as quick a test as is possible. If you run into problems, then adding a MsgBox command (MsgBox, %variable1% %variable2%) at the appropriate location in the script which will show the values of the current variables could instantly point to the solution. I do it all the time. You can remove the MsgBox command when the code is working. Also, placing a semicolon (;) before a line of code to temporarily "comment out" the line (the code line will be ignored) will help you determine if that line is the source of a problem. This is also a favorite of mine. This makes it easier to isolate the culprit if you don't know which code line has injected a problem.
When the hotkey combination CTRL++M is activated the dropdown menu pops up (see Figure 3 (bottom right)). The primary problem with the dropdown menu is its size which cuts off some of the text and the title of the menu. This lack of formatting is corrected by adding the GUI, FONT command and putting dimensions on the GUI, ADD and GUI, SHOW commands:
^#M::
Gui, Font, s12, Arial
Gui, Add, DropDownList, w275 , Select Position on the Screen
    ||Right Half of Screen|Left Half of Screen
    |Top Half of Screen|Bottom Half of Screen|
Gui, Show, W300 H40 , Move Window
Return

The GUI, FONT line sets the font size (12 pts) and font family (Arial) for the pop-up. In the GUI, ADD line the "w275" sets the width of the menu items to 275 pixels. In the GUI, SHOW line, the "W300 H40" sets the dropdown dimensions to 300 pixels wide by 40 pixels high. See the appearance of the new pop-up format at left.
We now have the dropdown menu set up. We can select items from the menu, but it doesn't do anything yet. Click the "x" in the upper right corner to close the pop-up. The next step is to set up the working dropdown list so that it actually does something.

Initiate Action from the Dropdown Menu

The first requirement is a variable for passing the selection to a subroutine. The variable Position, created with vPosition, will be used to pass the selection to the subroutine PosChoice created with the label gPosChoice. Both are inserted as options into the GUI, ADD line. Do not insert any additional commas in the option area.
^#M::
Gui, Font, s12, Arial
Gui, Add, DropDownList, w275 vPosition gPosChoice 
    , Select Position on the Screen||Right Half of Screen
    |Left Half of Screen|Top Half of Screen|Bottom Half of Screen|
Gui, Show, W300 H40 , Move Window
Return

PosChoice:
Gui, Submit, NoHide
MsgBox, This is the selection => %Position%
Return

There are a couple of errors I made when adding these options. The first was not creating the subroutine with the label name PosChoice. If AutoHotkey sees a newly created label (gPosChoice) in the options of a command, it looks for a subroutine with the same name (PosChoice:). If it isn't there, you get an error when the script is activated. Fortunately, the error window will tell you exactly what's wrong.
The second error was not including the GUI, SUBMIT line in the subroutine PosChoice. The submit loads the value of your selection into the variable Position. Without it the variable will be empty. It is not unusual to miss this kind of requirement.
As I mentioned, when something isn't working right I'll add a code line such as the "MsgBox, This is the selection => %Position%" (seen in the subroutine above) for displaying the value of a designated variable. When the variable showed up blank in the MsgBox, I remembered that the GUI, SUBMIT was required to set the variable value after making a selection. Then the message box displayed the selected value, see image at left. The NoHide option prevents the pop-up from closing after a selection is made which is useful if you want to change selections without reloading the script.
I may place an alert window such as the MsgBox shown at a couple of different points in the script to get specific information about what's happening. This can save a lot of time and guesswork. Later, I remove the MsgBox commands or just place a semicolon in front of the line so AutoHotkey will ignore it.
Using the text shown in the dropdown menu as the value for a variable is awkward, so by adding the option AltSubmit to the GUI, ADD line, the number of the item (1, 2, 3, 4, or 5) rather than the text will be stored in the variable value.
^#M::
Gui, Font, s12, Arial
Gui, Add, DropDownList, AltSubmit w275 vPosition gPosChoice 
    , Select Position on the Screen||Right Half of Screen
    |Left Half of Screen|Top Half of Screen|Bottom Half of Screen|
Gui, Show, W300 H40 , Move Window
Return

PosChoice:
Gui, Submit, NoHide
MsgBox, This is the selection => %Position%
Return

When adding the different window moving commands to the PosChoice subroutine, it will be easier (less wordy) to use the number of the item location on the dropdown menu rather than the actual text, although either would work.
There remains a number of issues that need to be resolved which may cause errors, plus the move commands must be added in a conditional set of statements. In the next chapter (Chapter Twelve) as we continue this journey, I explore the AutoHotkey commands for creating the "If" statements and how to calculate the window resizing and movement on the screen. For now, here is the entire script which when pasted into an AutoHotkey script should work as advertised:
^#M::
WinGetTitle, WinName, A

Gui, Font, s12, Arial
Gui, Add, DropDownList, AltSubmit w275 vPosition gPosChoice
     , Select Position on the Screen||Right Half of Screen|Left Half of Screen
     |Top Half of Screen|Bottom Half of Screen|Center of Screen|Top Right Corner
     |Bottom Right Corner|Top Left Corner|Bottom Left Corner|
Gui, Show, W300 H40 , Move Window
Return

PosChoice:
Gui, Submit, NoHide

    WinGetPos,TX1,TY1,TW1,TH1,ahk_class Shell_TrayWnd

    WinGetPos,X1,Y1,W1,H1,Program Manager
      X2 := W1/2
        Y2 := (H1-TH1)/2
  Y3 := H1-TH1
      X4 := W1/4
        Y4 := H1/4

If Position = 2
  {
        WinMove,%WinName%,,%X2%,0,%X2%,%Y3%
  }
If Position = 3
  {
        WinMove,%WinName%,,0,0,%X2%,%Y3%
  }
If Position = 4
  {
        WinMove,%WinName%,,0,0,%W1%,%Y2%
  }
If Position = 5
  {
        WinMove,%WinName%,,0,%Y2%,%W1%,%Y2%
  }
If Position = 6
  {
        WinMove,%WinName%,,%X4%,%Y4%,%X2%,%Y2%
  }
If Position = 7
  {
        WinMove,%WinName%,,%X2%,0,%X2%,%Y2%
  }
If Position = 8
  {
        WinMove,%WinName%,,%X2%,%Y2%,%X2%,%Y2%
  }
If Position = 9
  {
        WinMove,%WinName%,,0,0,%X2%,%Y2%
  }
If Position = 10
  {
        WinMove,%WinName%,,0,%Y2%,%X2%,%Y2%
  }

return

GuiClose:
Gui, Destroy

If you peruse this script you will see a number of additions which are needed to prevent other errors I encountered. This is all part of the normal programming debugging process which I continue in the next chapter.

Chapter Twelve: The Zen of the Script Writing Process (Part 2): Snapping Windows

“Writing AutoHotkey Scripts that Work...Eventually!”
Jack continues writing an AutoHotkey script for moving and resizing windows by learning the Windows screen coordinate system and adding the action.
Last time in "The Zen of the Script Writing Process (Part 1)" a dropdown menu was created using the AutoHotkey GUI command. I documented my errors while writing the script demonstrating the normal programming process of trial, error and correction.
Even though the script appeared at the end of the last chapter, I was nowhere near done. Maybe I took a break or even went to bed. While many scripts in AutoHotkey can be completed in a few minute or a few hours, a longer app will take considerably more time. This is where a calm meditative state of mind comes in. There will be times when finding bugs will seem impossible. You will stare blankly at the code wondering why it doesn't do what you want it to do. The more you scour your work the less you see. It's already two o'clock in the morning and you've been at it all day. Go to bed!
Stopping work isn't merely a matter of getting some rest and starting up again the next day. It is part of the Zen of programming. Your mind will not stop working even though you are asleep. It is not a conscious process, but it is very real. You may not even realize it's working—although you may also dream about your coding problem…but not in a rational way.
I can't tell you how many times I've gone to bed racking my brains about a coding problem. Sometimes I may work it out in my head while laying there. But just as often I sleep. When I wake in the morning, I go to the computer and solve the problem that wasted most of the day before in just a few minutes. Maybe it was because I was rested, but I know that it was all part of the process. Somehow my mind worked out where I should look and led me there. On some occasions I'm prompted to try a new approach to the problem. I often slap my head and say, "Duh! It's so simple!" Don't let these experiences deter or frustrate you—even while they are occurring. It is all part of the Zen of programming. Remember, just because you stop working, it doesn't mean your brain stops working.

Making It Happen

The final script shown at the end of the last chapter pops up a dropdown menu which will snap the last active window into a specific screen location and size (see Figure 1 and Figure 2).Figure 1. AutoHotkey dropdown menu for snapping windows.Figure 2. The last window is moved to the upper right-hand corner.
Now let's look at how we get there.
So far I had activated a pop-up which used the MsgBox command to display the value of the selection in another pop-up window. The next step is to build a conditional structure (IF command) to respond to each of the different options. This is done by adding the lines of code with MsgBox commands to indicate that it worked. In this case, since there are only four options so far, I added four conditionals:
^#M::
Gui, Font, s12, Arial
Gui, Add, DropDownList, AltSubmit w275 vPosition gPosChoice 
    , Select Position on the Screen||Right Half of Screen
    |Left Half of Screen|Top Half of Screen|Bottom Half of Screen|
Gui, Show, W300 H40 , Move Window
Return

PosChoice:
Gui, Submit, NoHide

Return
If Position = 2
     MsgBox, This is the selection => %Position%
If Position = 3
     MsgBox, This is the selection => %Position%
If Position = 4
     MsgBox, This is the selection => %Position%
If Position = 5
     MsgBox, This is the selection => %Position%
Return 

I copied "MsgBox, This is the selection => %Position%" into each If condition to see if it was working. Notice that there is no "Position = 1" in the list. That's because the first selection is the default "Select Position on the Screen" which has no associated action.
Since each "IF" response only consists of one line of code, it isn't necessary to enclose the line in curly brackets "{}" marking the beginning and the end of the section. However, I added them later, not because I needed them (I didn't), but for consistency and the possible future changes. This is a matter of personal preference. The conditional statements responded properly displaying the number of the selected item.
Note: There are a number of different ways to express conditionals in AutoHotkey. While the most standard may be using the IF command with the conditional code contained within curly brackets ({}), those brackets may be eliminated if there is only one line following the IF line, as shown in this example. You'll see later in the chapter that I switch to using the brackets. If there is any reason to believe that you may need to add more lines of code to the conditional, then it may be best to start off with the full bracketed system.
There is also another shortcut for the IF conditional where everything is contained on one line. It employs the % expression operator with the question mark (?) for the true code and the colon (:) for the else code. You can see this technique in action in Chapter Thirty-four.

Destroy the GUI for Resurrection

At some point in my testing, I noticed that I could only open the pop-up window once. If after closing I initiated the WindowMove program again, it caused an error. Since the variable Position was created on the first load, it couldn't be recreated on the second activation. That means I would need to "Reload This Script" (or Exit and reload for a compiled version) before I could use it again.
There are a number of solutions which make using the script multiple times without reloading possible. I settled on adding the following at the end of the script:
GuiClose:
Gui, Destroy

The built-in AutoHotkey window event label GuiClose: kicks in when you close the dropdown menu by clicking the "x" in the upper right-hand corner. "Gui, Destroy" removes the variables from memory so that they no longer exist. The next time you use the hotkey combination to open the dropdown menu, the variable is recreated and there is no error preventing you from continuing. The "Gui, Cancel" option would have the same effect in this situation.
There are other commands such as Exit and ExitApp which could have been used in the GuiClose subroutine to remove the dropdown from memory, but they would also exit the script. The hotkeys would no longer function without rerunning the script.

Adding Movement and Size

As you may have noticed, the programming process is not a matter of starting at the top and working through to the bottom—at least not in terms of writing the first line of code, then continuing straight to the end. It is more like building a structure where you start with a fundamental framework, get it functioning, then insert pieces as they are needed—often jumping back and forth inserting new lines of code between old ones. Now it's time to add the parts which will make it a finished product.
The script must grab an open window, resize it, and move it to a designated location. There may be many open windows. We need to know which one to grab. Then we need to know enough about the computer screen to determine the exact size and location to use for the target window. Finally, we make it happen.
The first step is identifying the target window. In this case, it's the active window at the time we press the hotkey combination. Clicking on the window we want to move, then pressing CTRL++M will be all we need to do. The first action in the script is capturing the window title for later identification:
WinGetTitle, WinName, A

The WinGetTitle command is used to read the active window's title (the "A" option) and store it in the variable WinName. Later, when the window is actually snapped into its new location with the WinMove command, the value of WinName is used to identify it.
Now we need to get the dimensions of the computer screen so we can calculate the required changes for the target window. For that we want an understanding of how the Windows screen and window location system works.

Understanding the AutoHotkey Screen and Window Location System

The window location and size system in AutoHotkey can be confusing. I know that I was disoriented a few times when I was putting together this script. Sometimes it is worthwhile to draw a graph to help understand the system for moving and sizing a window (see Figure 3). Once the system is understood it's relatively easy to figure out the proper coordinates and dimensions for moving windows around.Figure 3. The upper left-hand corner of the computer screen is located at x=0, y=0 (0,0). The x-axis runs from left to right and the y-axis runs from top to bottom. The location at the bottom right-hand corner is equal to the screen width and height and located at those coordinates (W1,H1).
The coordinate system starts in the upper left-hand corner at (0,0). From that point, x (the first number in the set) increases to the right and y (the second number in the set) increases in the down direction. All locations on the screen are represented by the combination of the x and y coordinates (x,y).
Tip: If you want to determine the coordinates (x,y) of various locations in windows or on the screen, you can use MouseGetPos to check the location of your last mouse click (see the figure at the left).
^#!M
MouseGetPos, mouseX, MouseY
MsgBox, You clicked here => %mouseX% %MouseY%
Return

Click on a window or the Desktop, then hit CTRL++ALT+M and a window will pop up. The x,y coordinates for the last mouse click are displayed for the appropriate window. If you want screen locations, then click on the desktop without an obscuring open window in the way. You can also use the AutoIt3 Window Spy program included with the AutoHotkey installation, Chapter Ten, displaying both the window and screen mouse click locations.

Capturing the Screen Size

In the script the WinGetPos command is used to save the size of the computer screen:
WinGetPos,X1,Y1,W1,H1,Program Manager

The "Program Manager" title designates the Windows Desktop screen as the target window. X1 and Y1 could be left blank since their value will always be 0,0 (upper left-hand corner of the computer screen), although the commas are required. W1 is the width of the screen in pixels. H1 is the height of the screen in pixels.
W1 and H1 are the two values needed to calculate location coordinates (midway points for both width and height) and the new window dimensions (half or full-width, half or full-height).
After I initially entered and tested what I considered the logical formulas for the windows (X2 = W1/2 and Y2 = H1/2) which give me the midway points and half widths and heights, I discovered that any windows extending to the bottom of the screen were partially hidden behind the Taskbar—not ideal. I needed to know the height of the Taskbar to subtract from the screen height. I added the following line of code:
WinGetPos,TX1,TY1,TW1,TH1,ahk_class Shell_TrayWnd

"ahk_class Shell_TrayWnd" designates the Windows Taskbar. (You can find this name by clicking on the Taskbar while the AutoIt3 Window Spy program,Chapter Ten, is open.) The only variable I needed was TH1, the height of the Taskbar to adjust the screen height and the y coordinate for half height windows.
The new formulas take the Taskbar height into consideration. The x coordinate and the width are unaffected since the Taskbar in not a concern for the horizontal dimensions (unless you've moved the Taskbar to the left or right side of the screen). The height for windows which take up the right or left side of the screen is Y3 = H1-TH1. The height for windows which cover the top or bottom half of the screen is Y2 = (H1-TH1)/2. X2 (midpoint horizontally) and Y2 (midpoint vertically) are the respective coordinates for non-zero locations.
In the final script which includes the four corners with quarter-screen size windows (top right corner, bottom right corner, top left corner, bottom left corner), the same values of X2 and Y2 are used appropriately for both the location and size of the windows. In all four cases the width and height are X2 and Y2 respectively.
The only other values calculated are used for centering a ? screen size window in the main screen. While the size remains the same (X2 wide by Y2 high), the location coordinate must be ? of the screen width and height (X4 = W1/4 and Y4 = H1/4).
The following are the lines of code which create the variable for locating and sizing the windows:
X2 := W1/2
        Y2 := (H1-TH1)/2
  Y3 := H1-TH1
      X4 := W1/4
        Y4 := H1/4

If at this point you're confused, I don't blame you. It is not always easy to follow all the gyrations necessary in a coordinate system to get the right results. However, if you're going to write other AutoHotkey scripts that manipulate windows on the Desktop, then you want to be comfortable with the coordinate system discussed here. If, after you finish the next part, you're foggy with what's been discussed, it may be worthwhile to go over this section again.

Moving the Windows

The WinMove command is added to each of the "IF" conditionals with the move and size parameters required for snapping the window identified by WinName. As I tested the code, I found that the windows were not necessarily moving or resizing the way I wanted. The format of the WinMove command is first the two coordinates (x,y) for the location of the upper left-hand corner of the window, then the two dimensions for the size (width and height) of the window. Get one parameter in the wrong place and you will see unwanted behavior. (The window may even move off the screen.) I had to look a little closer at what I was using (mostly coordinates flip-flopped) to get the right results. If I had added and tested the options one at a time, it may have gone a little easier.
Notice that WinName is enclosed in percent (%) signs. The same is true for the coordinate and dimension variables. This tells AutoHotkey to use the value of the variable rather than the text (variable name) when reading the command.
The following code shows the (almost complete) program with the first four options implemented:
^#M::

WinGetTitle, WinName, A

Gui, Font, s12, Arial
Gui, Add, DropDownList, AltSubmit w275 vPosition gPosChoice 
    , Select Position on the Screen||Right Half of Screen
    |Left Half of Screen|Top Half of Screen|Bottom Half of Screen|
Gui, Show, W300 H40 , Move Window
Return

PosChoice:
Gui, Submit, NoHide

    WinGetPos,TX1,TY1,TW1,TH1,ahk_class Shell_TrayWnd

    WinGetPos,X1,Y1,W1,H1,Program Manager
    X2 := W1/2
        Y2 := (H1-TH1)/2
  Y3 := H1-TH1

If Position = 2
       {
         WinMove,%WinName%,,%X2%,0,%X2%,%Y3%
       }
If Position = 3
       {
         WinMove,%WinName%,,0,0,%X2%,%Y3%
       }
If Position = 4
      {
        WinMove,%WinName%,,0,0,%W1%,%Y2%
      }
If Position = 5
     {
       WinMove,%WinName%,,0,%Y2%,%W1%,%Y2%
     }
Return 

GuiClose:
Gui, Destroy

Finishing the Script


The only code left to add is calculations and WinMove commands for the four corner ? screen size windows and one centered window. This can be done by copying and pasting the current "IF" conditionals, then modifying the selection number and adding the appropriate coordinate and dimension variables. (AutoHotkey was used to add the ? symbol seen in this text in the Web editing page of our e-book production program. To learn how it was done see Chapter Twenty-three, "Add AutoCorrection to Your Windows.")
The following is the final program code for the final WindowMove.ahk script which also can be downloaded from the ComputorEdge AutoHotkey Dropbox Web page :
^#M::

WinGetTitle, WinName, A

Gui, Font, s12, Arial
Gui, Add, DropDownList, AltSubmit w275 vPosition gPosChoice
     , Select Position on the Screen||Right Half of Screen|Left Half of Screen
     |Top Half of Screen|Bottom Half of Screen|Center of Screen
     |Top Right Corner|Bottom Right Corner|Top Left Corner|Bottom Left Corner|
Gui, Show, W300 H40 , Move Window
Return

PosChoice:
Gui, Submit, NoHide

    WinGetPos,TX1,TY1,TW1,TH1,ahk_class Shell_TrayWnd

    WinGetPos,X1,Y1,W1,H1,Program Manager
   X2 := W1/2
        Y2 := (H1-TH1)/2
  Y3 := H1-TH1
      X4 := W1/4
        Y4 := H1/4

If Position = 2
  {
        WinMove,%WinName%,,%X2%,0,%X2%,%Y3%
  }
If Position = 3
  {
        WinMove,%WinName%,,0,0,%X2%,%Y3%
  }
If Position = 4
  {
        WinMove,%WinName%,,0,0,%W1%,%Y2%
  }
If Position = 5
  {
        WinMove,%WinName%,,0,%Y2%,%W1%,%Y2%
  }
If Position = 6
  {
        WinMove,%WinName%,,%X4%,%Y4%,%X2%,%Y2%
  }
If Position = 7
  {
        WinMove,%WinName%,,%X2%,0,%X2%,%Y2%
  }
If Position = 8
  {
        WinMove,%WinName%,,%X2%,%Y2%,%X2%,%Y2%
  }
If Position = 9
  {
        WinMove,%WinName%,,0,0,%X2%,%Y2%
  }
If Position = 10
  {
        WinMove,%WinName%,,0,%Y2%,%X2%,%Y2%
  }
Return

GuiClose:
Gui, Destroy

It's All About the Process

Once you understand how it works, this window snapping script is not particularly complicated. Yet, even with its incremental simplicity a script can quickly become quite involved, and, if you're not careful convoluted. It's not uncommon for a programmer to write one working routine, only to later come back and eliminate many unnecessary lines of code. This happens because the programmer's understanding of the problem increases while working on the program. There is nothing wrong with this. It's all part of the Zen of script writing.
Normally, I present the AutoHotkey code, then explain how it works. This time I showed my thought process and the errors I made while writing this script. Why? Because it's especially important for people new to programming to understand that there is no perfect way to write code. Sometimes it will go smoothly while other times it will be difficult to overcome one small sticking point. There have been times when I have left a script in frustration, only to return later quickly coming up with the answer. ("I can't believe I didn't see it before!") There are always problems in programs. The satisfaction comes in solving those problems.
New programmers also should understand that there is no such thing as a perfect program. In most cases there are many different ways of coding the same thing. The goal is to write code that works. It may not be pretty, but if it gets the result, you've done your job.

Chapter Thirteen: Finding Lost Windows with AutoHotkey

“The Answer to a Question about Bringing Back a Lost Window with AutoHotkey”
While it may be rare that an open window can't be found, there are ways in AutoHotkey to locate and move all open windows.
John King of San Diego writes:
Here's an idea for a script that would use many of the same concepts of your windows-location script for a different purpose:
Most of us who work with computers have had the frustrating experience of "losing" an open window off the edges of the screen. It can sometimes be a real challenge to get the window back into the viewing frame. It would be useful to have an AutoHotkey script that when activated would display a list of the currently open windows, then upon selecting one, have that window's position reset to the center on the visible screen.
Perhaps you might want to challenge your readers to come up with such a script.
Thank you, John. You certainly pose an interesting problem. I gave it some thought and looked further into the capabilities of AutoHotkey looking for the simplest way to get it done. While introducing some new topics, this discussion is a little more advanced than many of the other AutoHotkey chapters, but the final script, once understood, is relatively simple. I discuss some code used in the development of this solution which does not appear in the final script because, as pointed out in the previous two chapters, the Zen of script writing is often a circuitous route before finally reaching app bliss.
First, we need a list of all the open windows. Then, that list of windows must be put into some type of selection menu structure. Last, when selected for the list, the target window is repositioned. The solution I developed highlights some features of AutoHotkey not previously discussed.

The List of Open Windows

The first step is building a list of open windows. Fortunately, AutoHotkey has a built-in WinGet command which makes listing open windows easy:
WinGet, OpenWindow, List
The term OpenWindow is the assigned array variable which holds the unique ID numbers of all existing open windows. If there are no additional parameters, the "List" command tells WinGet to get all open window ID numbers.
OpenWindow as an array is not just one variable, but represents a group of variables (OpenWindow1OpenWindow2OpenWindow3, etc.). The number of variables is equal to the number of open windows and stored in the single variable OpenWindow itself with no number added on. That simple one line command grabs the ID numbers of all the open windows, but now the problem is reading and using the list. An easy way to do this is with the Loop command. The Loop command can increment through the OpenWindow array displaying each window name:
WinGet, OpenWindow, List 



Loop, %OpenWindow% 

{ 

   WinGetTitle, Title, % "ahk_id " OpenWindow%A_Index% 

   WinGetClass, Class, % "ahk_id " OpenWindow%A_Index% 

   WindowList .= Title . "`n`t`tClass " . Class . "`n"

}



MsgBox, %WindowList%

Return
The Loop command repeats the routine enclosed within the curly brackets ({}) a specific number of times. In this case, the routine is repeated OpenWindow times which equals the number of open windows. As the routine is repeated the OpenWindow array index (A_Index) is incremented by 1. This makes it possible to look at each array variable (OpenWindow%A_Index%) one at a time.
Both the WinGetTitle command and the WinGetClass command are used to save specific information about each window in the variables Title and Class respectively. In both cases shown above, a single percent sign (%) is used to indicate that an expression rather than a variable is used to designate the ID number of the open window. When the variable is determined by an expression all text ("ahk_id ") is enclosed in quotation marks with the current variable name (OpenWindow%A_Index%) evaluating to the incremented variable (OpenWindow1OpenWindow2OpenWindow3, etc.). The single percent sign (%) has a different function from the percent signs found later in the same lines surrounding variables.
This is a little confusing since there are so many ways to display variables and text in AutoHotkey, but it is necessary to use expressions (the single %) when using or displaying arrays since only the index number (A_Index) differentiates each variable. This can be a difficult concept to grasp, but in essence OpenWindow%A_Index% is a variable which contains the name of a variable which contains the value of the open window ID (i.e., OpenWindow%A_Index% may equal OpenWindow1 which in turn stores the open window ID for the first open window). This makes it possible to increment through the various windows' IDs with the Loop command. Once understood, arrays are a powerful way to deal with lists of data.
Note: Some people would argue that this is not an example of a true array which in most programming languages may be multidimensional and usually enclose the indexes in parentheses or brackets. While this may be true, for our purposes this List command works very well as a single dimension array. The concept is the same and it is possible to simulate multidimensional arrays by using multiple indexes. (% ArrayVariable%Index1%%Index2%).

Concatenating (Adding) Strings (Text)

While incrementing through the open window IDs, the variable WindowList is used to store all data collected from the open windows:
WindowList .= Title . "`n`t`tClass " . Class . "`n"
This is notable because rather than using the percent sign to evaluate the variables and create the list, the alternative self-concatenating operator (.=) is used. The concatenation (adding) of text is done with the period ( . ) surrounded by at least one space on each side. The expression "WindowList .= Title ..." replaces "WindowList := WindowList . Title ..." in the above expression. (By using ".=" rather than ":=", the variable WindowList does not need to be repeated to add (append) text to itself.) All plain text must be enclosed within quotation marks. The same result could be obtained with:
WindowList = %WindowList% %Title% `n`t`tClass %Class% `n
With experience you may find that one method works better than the other in different situations for specific commands.
Note: I'm making a few assumptions about your level of experience with AutoHotkey. For example the special characters "`n" and "`t" in the line above are commonly used for new lines (`n) and tabs (`t). If you're new to AutoHotkey then you may want to check out the ComputorEdge AutoHotkey introductory Web page "Installing AutoHotkey and Writing Your First Script."
The script above displays the list of open windows in a message box (MsgBox, %WindowList%) as shown in Figure 1. Note that many of the open windows have blank titles and special classes. This information will be used to narrow down the list to only those windows that we may want to relocate.
Note: You could also place a message box (MsgBox) inside the loop to view the same data for each window as the Loop increments. This is what I did initially.
Figure 1. The message box displays a list of currently open windows. Note that many of the window titles are blank and some classes are associated with Windows Gadgets (circled in red).
When creating the GUI control which selects an open window and moves it to a better location, it will help to eliminate the system windows and gadgets circled in red in Figure 1. This will make the list shorter and easier to use.

The GUI Control for Selecting and Moving Open Windows

The DropDownList used in AutoHotkey Chapter Eleven is essentially the same one used in this application. The primary change is that the menu is created on the fly with the list of open windows. Plus the GUI control is set to +AlwaysOnTop to keep the control in view until done. The file result activated with the hotkey combination CTRL+WIN+L (CTRL++L) is displayed in Figure 2. The list of windows will change depending upon which windows are open at the time of activation.Figure 2. The AutoHotkey DropDownList shows the open windows. The system windows and gadgets have been filtered out of the list.
When a window title is selected, it is activated and moved to the coordinates 20,20 which should bring any window back onto the screen. If you would like a more sophisticated relocation and resizing, then use the techniques described in the second part of the "Snapping Windows" AutoHotkey column.
The final code for the WindowList.ahk script is as follows:
^#L::



Gui,+AlwaysOnTop

Gui, Font, s12, Arial

Gui, Add, DropDownList, w275 vWindowMove gPosChoice,Pick a Window||



WinGet, OpenWindow, List 



Loop, %OpenWindow% 

{ 

WinGetTitle, Title, % "ahk_id " OpenWindow%A_Index% 

WinGetClass, Class, % "ahk_id " OpenWindow%A_Index% 

If (Title != "" and Class != "BasicWindow" and Title != "Start" 

                and Title != "Program Manager")

   {

    GuiControl,,WindowMove, %Title%

   }

} 

Gui, Show, W300 H40 , Move Window

Return



PosChoice:

Gui, Submit, NoHide

WinActivate, %WindowMove%

WinMove, %WindowMove%,, 20, 20

Return



GuiClose:

Gui, Destroy

Return
Notice that only the first item is initially added to the DropDownList ("Pick a Window") as a default option which will do nothing. It is a little easier to add the items to the menu with the GuiControl command (GuiControl,,WindowMove, %Title%) inside the loop rather than storing all the data to one variable (WindowList, as previously discussed), since each item can be added as the routine increments through the Loop. The GuiControl command is useful for altering GUI objects after they have been created.
The only purpose of the "IF" conditional is to filter out unwanted windows. Most are skipped by eliminating all windows with no title (Title != ""). The double quotes represent a blank and "!=" means does not equal. Next the Windows Gadgets were eliminated by noting that they were of the "BasicWindow" class (Class != "BasicWindow"). The Start window (Title != "Start") and Program Manager window (Title != "Program Manager") are added individually to the "IF" conditions to filter out those Windows system windows.
When a particular window is selected, it is first activated (WinActivate, %WindowMove%), then moved to the coordinates X=20 and Y=20 (WinMove, %WindowMove%,, 20, 20). If you want a different location or to resize a window, then it can be done by altering this WinMove command.

Additional Notes

Suppose you want to use a similar routine to place four open windows in the four corners of the screen for simultaneous viewing. Using the calculations referenced in the second part of the "Snapping Windows" AutoHotkey column, you could move open windows (WinMove) to respective corners as they are selected.
Create a new variable and set it to 1 (MyNumber := 1). Add "IF" conditionals to the "PosChoice" routine for each WinMove location (MyNumber = 1, MyNumber = 2, MyNumber = 3, MyNumber = 4)—one for each corner. In the first three "IF"s, increment MyNumber by 1. In the fourth, reset MyNumber to 1. For example:
If (MyNumber =1)

{

   WinMove,%WindowMove%,,... ;move to first corner

   MyNumber := MyNumber + 1

 }

If (MyNumber =2)

{

   WinMove,%WindowMove%,,... ;move to second corner

   MyNumber := MyNumber + 1

 }

If (MyNumber =3)

{

   WinMove,%WindowMove%,,... ;move to third corner

   MyNumber := MyNumber + 1

 }

If (MyNumber =4)

{

   WinMove,%WindowMove%,,... ;move to fourth corner

   MyNumber := 1

 }
Remember the variable MyNumber needs to be created before the GUI is created. Otherwise, either the condition any of the four will never be met or the variable MyNumber will constantly be reset to 1. This program structure will move successively selected windows to the next corner based upon the coordinates and dimension you supply. This is a common technique used to increment a set number of times before resetting to 1.

Part III: AutoHotkey for Quick Backup of Your Work, Anywhere, Anytime!

“Learn how to create your own backup program while creating and writing text files.”
One of the most important Windows tools is one that backs up your current work, even when editing on the Web. In Part III Jack writes an AutoHotkey script that not only saves data but shows you how to create and write text files.
Not all Windows programs have automatic backup of your work and the Web editing windows certainly don't. That's why it's useful to use an AutoHotkey script to copy and save your work. This part of the book not only shows you how to write your own backup routine, but it introduces you to creating and writing text files with AutoHotkey. You will learn how to use a number of the AutoHotkey FILE commands while tailoring a practical application for your own use.
Chapter Fourteen: Protect Against the Pain of Losing Your Computer Work
A simple AutoHotkey script for temporary backup of new text whether on the Web or working locally.
"Suddenly your computer locks up or the power goes out for a split second. Your heart sinks as you realize that you've lost everything you were working on."
Chapter Fifteen: Incremental Backup to Protect Your Computer Work
An AutoHotkey System for Saving Changing Versions of Your Files
Many programs include incremental backup so you can recover earlier versions of your work. Now you can have that protection everywhere instantly with AutoHotkey.

Part III Index to Chapters

%, variable value (percent signs %), Chapter Fifteen
Backup scripts, Chapter FourteenChapter Fifteen
Backup, incremental, Chapter Fifteen
Removing special characters (\ and :), Chapter Fifteen
Return commandChapter Fifteen

Chapter Fourteen: Protect Against the Pain of Losing Your Computer Work

“A simple AutoHotkey script for temporary backup of new text whether on the Web or working locally.”
"Suddenly your computer locks up or the power goes out for a split second. Your heart sinks as you realize that you've lost everything you were working on."
I know that for some people the idea of writing short scripts of code (programming) is intimidating. However, if you can write an e-mail or short memo in Notepad, then you can easily make AutoHotkey work for you. It is that simple. This chapter will look at a solution for the computer crash or power outage problem when writing in computer programs or editing text in Web pages which have no built-in backup.

Losing a Half Hour of Work

Let's take a look at the following scenario: You're working with one of your regularly visited Web sites. It could be your bank, a Blogging site, your Web e-mail, or even Facebook. You're writing an extra long text message explaining the details of a problem (or your life). The Web site has no built-in Save button allowing you to store your work as you go along. Even if there is a Save button, it resubmits the entire page forcing you to relocate your place in your message. Maybe you're sending an e-mail to an institution, adding a comment to a forum thread, or posting your thoughts on Facebook. You've put a good deal of work into your screen and keep editing it to make sure that it's right.
Suddenly your computer locks up or the power goes out for a split second. Your heart sinks as you realize that you've lost everything you were working on. If you had first written the text in a word processor or Notepad, then you might have a backup—if you hit CTRL+S. But you didn't. It never occurred to you that the computer would crash, the Web site could temporarily become inaccessible, or the power might blip. It doesn't happen very often.
Wouldn't it be nice if you could save a copy of your in-progress text to a file without resubmitting that Web page or posting it to the world unedited—no matter which Web site you're visiting or what Windows program you're using? This can be accomplished with a short AutoHotkey script which turns the hotkey combination of CTRL+ALT+B into a backup feature writing all of your current text to a text file (SaveEdit.txt) saved in your Windows Documents folder. It works for Web editing windows (such as the one I'm currently using to write this chapter), in Notepad, WordPad, virtually any word processor, e-mail programs, or almost any other Windows program (see Figure 1). (The script will even save a list of files contained in an active Windows Explorer folder.)Figure 1. In-progress text is saved to a file called "SaveEdit.txt" (shown here when opened with Notepad) in the Windows Documents directory with the hotkey CTRL+ALT+B set up with an AutoHotkey script.

Writing Your AutoHotkey BackupText Script

If you already have AutoHotkey installed and running, then implementing BackupText.ahk is easy. First, you right-click on the Desktop or in your AutoHotkey folder and select New => AutoHotkey Script from the menu. A new window will open with your default text editor displaying the standard boiler plate shown in Figure 2. Next you copy and paste the code shown below Figure 2 into the new .AHK file and save it with the name BackupText.ahk. Finally, right-click on the new file name and select Run Script. Now the hotkey combination CTRL+ALT+B will copy any text you are currently working on and save it in the file SaveEdit.txt located in your Windows Documents folder.Figure 2. The AutoHotkey BackupText.ahk script contains boilerplate added when the script was created and the code to instantly backup your current work.

The BackupText Script AutoHotkey Code

To implement the new backup hotkeys, copy and paste the following code into an AutoHotkey file:
^!B::
Send, ^a
Sleep 100
Send, ^c
Sleep 100
IfExist, C:\Users\%A_UserName%\Documents\SaveEdit.txt
  {
    FileDelete, C:\Users\%A_UserName%\Documents\SaveEdit.txt   
  }
FileAppend , %clipboard%, C:\Users\%A_UserName%\Documents\SaveEdit.txt
Click
return

How the BackupText Script Works

While this AutoHotkey routine may look complicated to some people, when taken one line at a time it is actually quite simple.
The first line (^!B::) establishes the hotkey combination CTRL+ALT+B. The caret mark (^) represents CTRL. The exclamation point is the ALT key. Of course, B is the letter B on the keyboard. The double colon (::) marks the end of the hotkey combination and the beginning of the AutoHotkey code.
The second line of code (Send, ^a) uses the AutoHotkey Send command to execute the standard Windows key combination CTRL+A to select all of the text in the current editing field or window. The text and background changes color to show that it is selected (see Figure 3).Figure 3. When CTRL+A is sent by the AutoHotkey script the text and background changes color to show that the text is selected.
When the script is executed the change in color caused by the ^A will appear as a flash.
The third and fifth lines (Sleep 100) merely cause a pause in the script (one tenth of a second) to allow the completion of the previous line before moving on. Otherwise, the script may be completed with old values.
The fourth line of code (Send, ^c) uses the Send command to copy (CTRL+C) the selected text into the Windows Clipboard.
The sixth line of code uses the IfExist conditional to check for the file SaveEdit.txt in the Documents directory. If the file does exist, it will be deleted with the FileDelete command (FileDelete, C:\Users\%A_UserName%\Documents\SaveEdit.txt). Otherwise the FileAppend command used below would continue to add text to the same file rather than replacing the old text with the new text. If the file does not exist, the FileAppend command will automatically create it—which it does in every case since the old file (if found) is always deleted.
Note that the logged on user variable A_UserName is used in the path. This makes the routine universal by substituting the current user's name—regardless of the user.
In the FileAppend line:
FileAppend , %clipboard%, C:\Users\%A_UserName%\Documents\SaveEdit.txt

The contents of the clipboard are saved to the file SaveEdit.txt which is created on the spot in the Documents folder of the logged on user A_UserName.
The last command issued before the end of the routine is the mouse Click command. This is included to deselect the currently selected text. Otherwise hitting any key could cause all of the text to disappear. (If you inadvertently delete selected text, you can usually get it back by either selecting Undo from the Edit menu—if there is an Edit menu—or right-click and select Undo from the menu.)
The Return command marks the end of the routine.

Problems with Backup

For many people this backup routine will be sufficient for those times when temporary backup is needed. Yet, there are a couple of issues with using this example. The first is that it is not automatic. You're required to hit the hotkeys to make it work. If you don't use it, you'll have no more protection than usual.
You could consider putting code in a timer which would automatically create a new backup at regular intervals, but in its current form you might accidentally delete all your text if it is activated while you're typing. (Using the Critical command in the first line after the double colon should prevent this problem since it would buffer keystrokes until the execution of the AutoHotkey routine is complete. We have yet to explore putting routines on a timer.) Another problem with a timer routine is that it will backup whatever window you happen to be on when it is executed, regardless of the type of window. This could cause the text you want to save to be overwritten, thus losing your backup.
An additional issue with this routine is that there is only one backup file. (That's why I call it temporary backup.) Anytime you use it, it wipes out the last backup. To resolve this problem the routine can be changed to use the window title in the file name (easier to recognize) and a unique identifier to allow incremental backup. This would ensure that nothing is lost since a new, unique, easy to identify file name would be created every time the routine is executed. The downside is that many more files will be saved taking up more storage space.
In the next chapter, using the windows names and unique identifiers in backup file names will be explored.

Chapter Fifteen: Incremental Backup to Protect Your Computer Work

“An AutoHotkey System for Saving Changing Versions of Your Files”
Many programs include incremental backup so you can recover earlier versions of your work. Now you can have that protection everywhere instantly with AutoHotkey.
In Chapter Fifteen, I discussed creating a temporary backup that can be used at any time to save text that you're writing whether in a Windows program on your computer or while working in a Web text editing field. I've added that to my list of AutoHotkey hotkeys and find that I use it all the time—especially when working on the Web which has no automatic backup. Then, if there is a power outage or I just hit the wrong button (accidentally closing the browser window), I can go back to the text file created with the hotkeys and recover my work as of the last time I hit the combination.
However, as I pointed out, that temporary backup only uses one file which is replaced every time I hit the hotkeys. If I want to save more copies of different windows and/or incremental copies which include older backups, then I need to do a little bit more. The routine offered in this chapter does just that.

Incremental Backup for Various Windows

To do incremental backup you need a method for creating unique file names. That way you won't accidentally overwrite an old backup file with a new one. In most cases, the easiest technique for doing that is by using a file or program name plus the current time. Since the time measured to the second (or microsecond, if necessary) never repeats itself, as long as you do not backup two items in the same second, you can create unique file names for the backups. It's merely a matter of incorporating the current time into the file name (see Figure 1).Figure 1. The saved incremental file name is composed of the window title and the current time to the second.
The AutoHotkey routine which is creating the file names in Figure 1 for the text saved in the associated file uses the title of the window plus the current time. These backup files were created while editing a text file in Notepad for the description of the Windows 8 e-book for Amazon.com. The backup file name includes the text file name (Win 8 Amazon.txt), the editing program (Notepad), plus the time the backup was made with the hotkey combination CTRL++ALT+B (B for Backup). The backup files are saved in the My Documents => Backup folder. If the Backup folder does not exist, the routine creates it.
The same AutoHotkey program was tested with an Apple Web page comparing iPad models, the Windows Calculator, ComputorEdge Web editing software, and two different Windows File Explorer listings—one of which is the Backup folder itself (see Figure 2). Each time the CTRL++ALT+B combination is hit, a new backup file is created.Figure 2. Each time the backup routine is executed a new backup file is created.
The Windows Calculator backup was create by executing CTRL++ALT+B while the calculator was active (see Figure 3).Figure 3. The AutoHotkey backup routine even works with Windows Calculator.
Open the associated Calculator backup text file (Calculator20121127154632.txt) and you will see the same value saved from the calculation (see Figure 4).Figure 4. The value seen in the Windows Calculator is saved to a backup file.
If a "Documents - Backup" text file is opened, a list of the files contained in the Backup folder at the time the hotkey combination was used is opened (see Figure 5). For this to work, code to convert special characters such as the colon (:) and the backslash (\) to regular text is required as shown in Item E of Figure 6. If you don't plan to save file lists from Windows File Explorer, then you won't need this code.
Figure 5. The list of files in the Backup folder is saved to a backup text file. This requires code to deal with special characters found in the file path. See Item E in Figure 6.
This AutoHotkey routine is flexible and works with most active windows. However, while it works with Web pages such as the Apple page noted, the formatting of the text (tables and other HTML tags) will affect how it appears in the backup text file. It will not be a WYSIWYG (What You See Is What You Get) copy of the Web page. It only copies text (no images).

The IncrementalSaveText.ahk AutoHotkey Routine

While a little more involved that the AutoHotkey routine used last time for the temporarily backup file, once broken down, the IncrementalSaveText.ahk routine is easy to understand (see Figure 6).Figure 6. The AutoHotkey code for incremental backup of active window text. A. The assigned hotkey combination (CTRL+WIN+ALT+B). B. Select text and copy to the Windows Clipboard. C. If Backup folder does not exist, create it. D. Assign the window title to variable WindowName. E. For saving file lists in Windows File Explorer, replace special characters found in file paths. F. Create incremental file with Windows Clipboard contents using the window title and current time. G. Deselect text and end AutoHotkey routine.
To use the IncrementalSaveText.ahk routine, cut-and-paste the following code to either a new AutoHotkey file or an existing one:
; Copying text to C:\Users\%A_UserName%\Documents\Backup\[incremental filename].txt for backup

^#!B::
Send, ^a
Sleep 100
Send, ^c
Sleep 100

IfNotExist, C:\Users\%A_UserName%\Documents\Backup\
{
  FileCreateDir, C:\Users\%A_UserName%\Documents\Backup\
}

WinGetTitle, WindowName, A

StringReplace, WindowName, WindowName, `\, -, All
StringReplace, WindowName, WindowName, `:, -, All

FileAppend , %clipboard%, C:\Users\%A_UserName%\Documents\Backup\%WindowName%%A_Now%.txt
Click
return

How It Works

Both Items A and B in the code (see Figure 6) are essentially the same code used in the example from last chapter, except in this case the hotkey combination is ^#!B (CTRL++ALT+B). The text in the active window or field is selected (Send, ^a) and copied to the Windows Clipboard (^c). The Sleep command is used to pause the routine in order to allow enough time for the completion of each step. It might be necessary to increase these sleep times if you're copying larger amounts of text such as the Apple Web page noted above.
The code shown in Item C is necessary only if the folder Documents/Backup does not already exist. The IfNotExist command checks for the existence of the folder. If it is not there the FileCreateDir command is used to create it. If you plan to create the folder yourself, then this code can be eliminated.
The line of code in Item D (WinGetTitle, WindowName, A) uses the WinGetTitle command to store the window's title of the active window (A) to the variable WindowName. This is used as the first part of the file name for the backup file.
In two lines of code in Item E the StringReplace command is used to remove the special characters (backslash and colon) which will prevent the routine from working for Windows File Explorer. Both are replaced with the hyphen (-) creating an innocuous file string to use in a file name. Note that the AutoHotkey escape character (`) precedes the special characters (\ and :). This is to ensure that they are treated as plain text and not their special character function.
The line of code in Item F uses the FileAppend command to create a unique file which contains the copied text in the Clipboard by combining the window's title WindowName with the current time A_Now and ".txt" for the file name. Note that the variables ClipboardA_UserNameWindowName, and A_Now need to be enclosed in percent signs (%) to return their value rather than the variable name itself.
The Click command in Item G deselects the text in the current active window. This protects against accidental deletion of the selected text when hitting another key. The Return command marks the end of the routine.
Many programs such as Notepad++ have internal settings for incremental backup (Verbose backup) which use a similar backup naming system of the current file name plus date and time. But if you want an alternative incremental backup which will work in any editor including Notepad, WordPad and on the Web, then this AutoHotkey routine will give you a little more flexibility—plus it also works in Notepad++.

Part IV: Collect Data in One Pot

“This handy AutoHotkey trick for copying from one window to another is a must have for anyone who collects Web information.”
Not only will you learn how to quickly collect data, but a free AutoHotkey Scratchpad app by another script writer is introduced as an example of what AutoHotkey can do. It uses an INI file to save setup parameters.
When doing research on the Web, it can be helpful to quickly copy-and-paste quotes and URLs into another document—either as part of an article or for future reference. The copying, switching windows, pasting, then switching back to the original windows can become tedious. In AutoHotkey there are simple techniques for automating the process. In Part IV, these data collection tricks are demonstrated, plus Jack gives an introduction to INI files for saving settings. Later in Part VIII: Introduction to Databases, Calculating Ages, and Formatting Problems, an INI file is used to show how to set up and use a database in the GrandKids app.
Chapter Sixteen: How to Collect Web Page Text, Web Addresses, and Other Info for Research in One Pot
With AutoHotkey you can build a tool for collecting data.
This tool for collecting text from Web pages, e-books, documents or any other source is helpful to reporters, students, business people, researchers, or anyone else who needs to work from multiple sources.
Chapter Seventeen: A Free Scratchpad App
Scratchpad is a simple, quick, free app that makes it easy to take notes.
While you could save notes to an open Notepad window, Scratchpad has the advantage of popping up and disappearing quickly at the stroke of a key combination.
Chapter Eighteen: Instant Paste in Scratchpad and Using INI Files
How to use an AutoHotkey instant paste technique and saving AutoHotkey app values in an INI file.
Copy quotes into Scratchpad without changing windows, plus how to use an INI file to save key parameters and variables in AutoHotkey scripts.

Part IV Index to Chapters

Adding a Help window (Scratchpad script), Chapter Seventeen
Adding to an AutoHotkey control, Chapter Eighteen
Always-on-top (Scratchpad script), Chapter Seventeen
Comments in scripts (;), Chapter Sixteen
ControlSend commandChapter Sixteen
Copy text to another window, Chapter Sixteen
Visible, toggling a window (Scratchpad script), Chapter Seventeen

Chapter Sixteen: How to Collect Web Page Text, Web Addresses, and Other Info for Research in One Pot

“With AutoHotkey you can build a tool for collecting data.”
This tool for collecting text from Web pages, e-books, documents or any other source is helpful to reporters, students, business people, researchers, or anyone else who needs to work from multiple sources.
If you have a reason to cite text from Web pages, e-books, documents or any other computer source which allows copying (CTRL+C), then you may want to collect all these bits of information in one place without the continual jumping between two windows (select, copy with CTRL+C, move to collection window, paste with CTRL+V, then return to source and do it all over again). The AutoHotkey routine below takes most of the work out of collecting quotes, references, URLs of Web sites, or any other text-based information. This is helpful to reporters, students, business people, researchers, or anyone else who needs to work from multiple sources. I've called the snippet of AutoHotkey code SendText.ahk.

What the SendText AutoHotkey Routine Does

Imagine that you are surfing the Web looking for interesting information. You come upon the Wikipedia page for Universal Serial Bus. You see information that you want to save in a text file. You select the desire text (see Figure 1).
Figure 1. Text is selected from a Web page for sending to a new Notepad file.
Next you press the hotkey combination CTRL+ALT+S. A new Notepad window is opened and the text is added (see Figure 2).
Figure 2. Notepad is loaded and the selected text is added to the open window.
Of course you also want to save the URL (Web address) for the text you have added to Notepad. You return to the Web browser window and highlight the URL in the address field (see Figure 3).
Figure 3. The URL for the previously sent text is selected for adding to the open Notepad window.
Now, using the same hotkey combination (CTRL+ALT+S), the URL is added to the original Notepad window (see Figure 4).
Figure 4. The selected URL is added to the original Untitled Notepad window.
This can be done over and over again, adding more text to the same Notepad window while moving from one Web page (or any other document) to another. This process will continue until you save the Notepad text with a new file name. Notepad is merely acting as a collection box for your research.

The SaveText Routine

The SaveText.ahk routine is a little more involved than some of the simple AutoHotkey examples, but once you understand the purpose of each line of code, it becomes clear. After copying the selected text to the Windows Clipboard, the routine looks for an open Untitled Notepad window. If it finds one, it activates the window and pastes the text into it. If an Untitled Notepad is not found, the routine Runs Notepad to create one, then adds the Clipboard text to the new window (see Figure 5).Figure 5. The code for the SaveText routine checks for an open Untitled Notepad window.
To use this routine, copy and paste the following code into one of your AutoHotkey scripts or a newly created script:
; Copying text to Notepad for saving
^!s::
Send, ^c

IfWinExist, Untitled - Notepad
{
  WinActivate  ; Automatically uses the window found above.
}
Else
{
  Run, Notepad
}
WinWaitActive, Untitled - Notepad
Send, ^v`n`n
return

Note: If you already had this AutoHotkey routine running, you could copy it to a new Notepad file by selecting it, using the hotkey combination CTRL+ALT+S, then saving the file as SaveText.ahk, although it would not contain the usual boilerplate shown in the top portion of Figure 5.

How it Works

Note on comments in scripts: Remember that any text following a semicolon (;) is merely a comment for clarity and is not seen or executed by the AutoHotkey program. This is the case for the first line of the code in the routine.
The first line of executable code (^!s::) designates CTRL+ALT+S as the hotkey combination used to activate the routine. See the Hotkeys list for the symbols used by various keyboard keys. The double colon marks the end of the hotkey sequence and the beginning of the routine.
The second line (Send, ^c) uses the Send command to copy the selected text to the Windows Clipboard. If no text is selected, whatever was last saved in the Clipboard will be used.
The third line (IfWinExist, Untitled - Notepad) uses the IfWinExist command to check for an open window with an "Untitled - Notepad" title. The title "Untitled - Notepad" is given to all new instances of Notepad where a file has not been designated. If there is more than one such Notepad window open, AutoHotkey will use the last one activated. If you save the Notepad window with a new file name, this routine will no longer find the window (different name) and open a new window with Notepad.
Since there is only one line in both portions of the If/Else, I could have omitted the sets of curly brackets ({}). However, I have put them in for consistency while leaving the option to add more lines of code to either section.
If IfWinExist is true (an open "Untitled - Notepad" is found), then the window activates with the WinActivate command. If IfWinExist is false, (no open "Untitled - Notepad" is found), then the Run command (Run, Notepad) opens a new Notepad window.
After the If/Else conditional, the routine waits until the Notepad window is active (WinWaitActive, Untitled - Notepad). This waiting is necessary to ensure that the paste operation is not executed before the window is available. Otherwise, the text may never be entered into Notepad.
The last line of code before the Return—which marks the end of the routine—uses the Send command (Send, ^v`n`n) to paste the Clipboard text into the Notepad window. Note the two special characters (`n`n) at the end of the line. These are AutoHotkey escape characters used to add two carriage returns to the end of the text. This way there will be a blank line between every new text selection sent to the Notepad window.
With modifications this same procedure can be used with other applications such as WordPad, Paint, and your word processor. In many of those programs, if supported, you can send selected images as well as text to the open window.
Another option is to add a specific file name to the routine, rather than Untitled. This will allow you to save the file every time you paste new selections by adding a Send, ^S line of code (for save) right after the Send, ^V line of code. Add a Send, ^{End} line before the Send, ^V line of code to ensure that the cursor jumps to the end of the file.
If you don't want the Notepad window to pop up every time you select and send text, then use the ControlSend command:
^!s::ControlSend, , ^V, Untitled - Notepad

In this case you don't need or want to activate the Notepad window as long as it is the last "Untitled - Notepad" you activated. The WinActivate and WinWaitActive commands should be removed and the IfWinNotExist command can be used for the Run without an Else.

Chapter Seventeen: A Free Scratchpad App

“Scratchpad is a simple, quick, free app that makes it easy to take notes.”
While you could save notes to an open Notepad window, Scratchpad by Desi Quintans has the advantage of popping up and disappearing quickly at the stroke of a key combination.
This time we look at another free Windows app called Scratchpad by Desi Quintans (see Figure 1). I found the app on the AutoHotkey Web site and highlight it because it's another free app that you can run without AutoHotkey or any other installed program, plus it has some interesting AutoHotkey techniques if you care to peruse the code. Scratchpad is a quick tool for taking notes while working on your computer or browsing the Web. It pops up with WIN+S (+S) and hides with either WIN+S or Escape.Figure 1. The Scratchpad app allows you to take notes in a separate pop-up window which can be saved to a time/date labeled text file.
Scratchpad is a quick-and-dirty solution for anyone who needs this type of tool. It could be especially useful for students collecting notes and references from e-books or Web sources. You don't need to know anything about AutoHotkey to use this app since after downloading and extracting the EXE file from the ZIP file, a double-click will load it on any Windows computer. A pencil and paper icon is placed in the Windows System Tray on the right side of the Taskbar. Right-click on the icon to exit the app, plus use the Show/Hide as an alternative to the +S hotkey combination (see Figure 2). The hotkey can be changed to any other letter, however unchecking the Win box appears to disable hotkey completely.Figure 2. Right-click on the Scratchpad icon in the System Tray to Exit or Show/Hide the Scratchpad.
The Scratchpad stays always-on-top when active allowing you to move around other windows without losing sight of it. Click the question mark (?) in the lower right-hand corner to see Help.
If you have a little knowledge of AutoHotkey, the source script (AHK) is included in the downloaded ZIP file. It is not a complicated script for AutoHotkey programmers with a little experience. I've included the Scratchpad.ahk script in the next chapter because it employs some useful techniques and there are simple additions which can add a good bit of value to the app.
It is worthwhile to study scripts written by other people, especially if those script accomplish tasks similar to those you want done. When starting a new script or looking for a way to make AutoHotkey do something in particular, I will often look for examples on the Web. Unfortunately, many of the examples are far too convoluted to use as a guide, but Desi Quintans' Scratchpad is an exception. His code is relatively straight forward and offers a number of new techniques, such as, the use of an INI file to save setup information from session to session (discussed in Chapter Eighteen).
Note: If you're concerned about downloading and running an EXE file, the source code is included in an AHK file (which is text only) in the same ZIP folder. You can compile the AHK file yourself with AutoHotkey bypassing any EXE file that may worry you. See "Installing AutoHotkey and Writing Your First Script."

Add Instant Paste to Scratchpad

When extracting quotes from other digital sources such as e-books and Web pages, the always-on-top feature of Scratchpad makes it easy to copy-and-paste quotations. However, there is an AutoHotkey technique (Chapter Sixteen) which will automatically move highlighted text into another window with a hotkey combination (see Figure 3). It does the copy-and-paste operation for you. It is only a few lines of code which can easily be added to the Scratchpad.ahk script or reside in a separate AutoHotkey script.Figure 3. It's possible to add a code to the Scratchpad script which automatically copies selected text for any source to the Scratchpad editing field.
In addition to the copy-and-paste routine and an introduction to INI files discussed in the next chapter, the Scratchpad.ahk script includes the use of GoSub, adding a Help window, setting always-on-top, toggling a window visible, and saving a file on exit. There is a lot of good grist for consumption.

Chapter Eighteen: Instant Paste in Scratchpad and Using INI Files

“How to use an AutoHotkey instant paste technique and saving AutoHotkey app values in an INI file.”
Copy quotes into Scratchpad without changing windows, plus how to use an INI file to save key parameters and variables in AutoHotkey scripts.
This chapter serves a dual purpose. First the code to add an instant paste feature to the Scratchpad app, highlighted in Chapter Seventeen, is discussed. Second, the Scratchpad app code is examined to show how it uses an INI file to save setup parameters for use from one session to the next. This is our first introduction to saving data other than text (chapters on AutoHotkey backup scripts) in files. These INI file techniques will be applied ultimately in the Reminder app discussed in Part VII: "Building the Reminder App Step by Step" and Part VIII: "Introduction to Databases."

Add Instant Paste to Scratchpad

As I mentioned in the last chapter a good feature to add to the Scratchpad app would be an instant paste that automates copy-and-paste from any other source to the Scratchpad editing window (see Figure 1). To instant paste, you merely highlight the desired text, then hit the hotkey combination. The text is copied to Scratchpad at the location of the cursor.Figure 1. It's possible to add a code to the Scratchpad script which automatically copies selected text from any source to the Scratchpad editing field.
A similar technique for copying from a source to Notepad was discussed earlier in Chapter Sixteen. However, the command used in that script (SEND) would not work in this case since Scratchpad uses an edit field within an AutoHotkey control rather than a regular window or program. In this case adding code similar to the following to either the Scratchpad script or a new separate AutoHotkey script would do the trick:
  ^#J::
  Send, ^c
  ControlSend, Edit2,  ^v`n`n, Scratchpad
  Return

The first line establishes the hotkey combination CTRL++J (^#J before the double colon ::). This can be any combination that works for you without interfering with other hotkeys in Windows and other programs. I use more than one function type key, such as CTRL, ALT, WIN, and SHIFT, with a letter in the hotkey combination because they are in close proximity (easy to reach with one hand) while making it less likely that the combination will interfere with other hotkeys.
The second line of code (Send, ^c) uses the SEND command to copy (CTRL+C) the selected text. If no text is selected, the current Clipboard contents are used.
The third line of code (ControlSend, Edit2, ^v`n`n, Scratchpad) uses the ControlSend command to paste (^V) the Clipboard contents into the edit field (Edit2) in the Scratchpad window. The two "`n" characters are new lines added at the end of each new paste.
The names of the edit fields can be determined with AutoIt3 Window Spy, Chapter Ten, which is installed with the AutoHotkey program and can be loaded directly or with a right-click of the System Tray icon of a loaded AHK file.
The RETURN command ends the routine.
I've found this technique particularly easy and useful for collecting multiple quotes and information in one place from a variety of sources.

Saving AutoHotkey Script Setup Information

A problem with AutoHotkey scripts is that they run in memory which is temporary. If you close the app or shut down the computer, anything in memory is lost unless it is first saved to the hard drive or other permanent storage. There are a number of ways to save data in AutoHotkey. Two of them are employed in the Scratchpad app. The first is when the text put in the Scratchpad is saved to a date/time labeled text file or any name you like when you use Save As (CTRL+SHFT+S). The second is the saving of parameters to be used from session to session in an INI configuration file.
The INI file goes back to the days of MS-DOS when they were used for "initialization" of the system and various programs. They contained data required for setup and configuration of the computer operating system. The INI file uses a simple basic format. In the Scratchpad folder there is a file called ScratchpadData.ini. (The file is created the first time Scratchpad is loaded.) See Figure 2.Figure 2. The ScratchpadData.ini file shows one section [Settings] and seven keys which equate to variables in the script.
An INI file has two parts: sections and keys. The sections are enclosed in square brackets ([...]) and use a label as a name. There may be any number of sections in an INI file as long as there are no duplicate labels. The keys are listed below the section and are set to values with the equals sign (=). AutoHotkey includes INI commands (IniReadIniWrite, and IniDelete) specifically for reading and writing INI files. The beauty of the INI file system is that it is easy to use without involved data parsing within the file.
Within Scratchpad.ahk there are two labels (routines) which work with the INI file: WriteToIni and ReadFromIniWriteToIni creates and updates the file ScratchpadData.ini:
WriteToIni:
      IfExist, ScratchpadData.ini
            FileDelete, ScratchpadData.ini

     IniWrite, %SaveOnExit%, ScratchpadData.ini, Settings, SaveOnExit
        IniWrite, %StartMinimised%, ScratchpadData.ini, Settings, StartMinimised
        IniWrite, %VisibilityHotkey%, ScratchpadData.ini, Settings, VisibilityHotkey
    IniWrite, %UseWinkey%, ScratchpadData.ini, Settings, UseWinkey
  IniWrite, %LastActiveFile%, ScratchpadData.ini, Settings, LastActiveFile
        
    WinGetPos, WinX, WinY,,,Scratchpad (desiquintans.com/scratchpad)
     IniWrite, %WinX%, ScratchpadData.ini, Settings, WindowPositionX
 IniWrite, %WinY%, ScratchpadData.ini, Settings, WindowPositionY
return

The IniWrite command saves the value of a variable (%SaveOnExit%) to the INI file (ScratchpadData.ini) in the section (Settings—the brackets are not used here) to the key (SaveOnExit).
Note in the above routine that if the file already exists (IfExist, ScratchpadData.ini), it is deleted (FileDelete, ScratchpadData.ini). This gives a clean start, but it isn't necessary since the first time IniWrite is executed it will create the file and on subsequent uses of the IniWrite command the same keys will be updated as long as the section and key name remain the same. This allows you update key values on the fly without rewriting the entire file.
To save the last position of Scratchpad, the WinGetPos command (WinGetPos, WinX, WinY,,,Scratchpad (desiquintans.com/scratchpad)) is used prior to writing the Scratchpad screen coordinates to the INI file.
The ReadFromIni label (routine) uses the IniRead command to recall the values of the previous IniWrite commands:
ReadFromIni:
    IfExist, ScratchpadData.ini
    {
           IniRead, newSaveOnExit, ScratchpadData.ini, Settings, SaveOnExit
                IniRead, newStartMinimised, ScratchpadData.ini, Settings, StartMinimised
                IniRead, newVisibilityHotkey, ScratchpadData.ini, Settings, VisibilityHotkey
            IniRead, newUseWinkey, ScratchpadData.ini, Settings, UseWinkey
          IniRead, LastActiveFile, ScratchpadData.ini, Settings, LastActiveFile
           IniRead, WinX, ScratchpadData.ini, Settings, WindowPositionX
            IniRead, WinY, ScratchpadData.ini, Settings, WindowPositionY
            
            GuiControl,, SaveOnExit, %newSaveOnExit%
          GuiControl,, StartMinimised, %newStartMinimised%
          GuiControl,, VisibilityHotkey, %newVisibilityHotkey%
              GuiControl,, UseWinkey, %newUseWinkey%
            GuiControl,, History, %LastActiveFile%
            
            WinMove, WinX, WinY
       }
return

Note that this routine checks for the existence of the file before reading to prevent using anything but default parameters established in the app.
The format of the IniRead command is similar to the IniWrite command except that the value to be written is replaced with a variable to store the read value. The IniRead command saves the key value to a variable (newSaveOnExit) from the INI file (ScratchpadData.ini) in the section (Settings—the brackets are not used here) of the key (SaveOnExit).
In the second section the GuiControl command is used to set the Scratchpad window values, hotkey, and reposition the window.

Part V: Quick Launch Links and Menus

“Two different AutoHotkey techniques for adding Start windows and menus to your Windows computer, plus compiling AutoHotkey scripts to EXE files.”
See how to use both AutoHotkey GUI windows and the MENU command to create pop-up menus for launching your most used programs and opening favorite Web sites. Plus, adding specialized menus to the System Tray and compiling new icons.
While there are many ways to launch programs and Web sites in Windows, it's helpful to pull them all together into one menu. In all versions except Windows 8, this could be done on the Start Menu. Now with AutoHotkey you can create a tailored menu structure for your personal or business needs. (These techniques can even be used to replace the missing Start Menu in Windows 8.) In Part V, two different approaches are taken adding menu structures for favorite items. The first uses an AutoHotkey GUI window to set up the launch of commonly used programs. The second uses the MENU command to build a pop-up menu structure from a QuickLinks Windows folder. Both are flexible and adaptable to your needs while showing the power of AutoHotkey.
In Chapter Twenty-two the QuickLinks script is tweaked to add the menu structure to the System Tray icon's right-click menu, plus the EXE compiler is discussed.
Chapter Nineteen: Make Your Own Start Pop-up for Windows
Add a new Start window to any version of windows including Windows 8!
Missing the Start Menu in Windows 8 or want to do more with any version of Windows? Now you can create your own tailored Start windows for any of your Windows computers with AutoHotkey.
Chapter Twenty: A Free QuickLinks Windows App from Jack
All your favorite programs, Web sites and documents are only a click away.
Jack offers a simple, easy to use, free app which can replace both the Windows Taskbar and Start Menu links (even in Windows 8). Guaranteed safe. Jack should know. He wrote it.
Chapter Twenty-one: How to Make a Pop-up Menu for Programs, Web Sites and Files
Reading files from folders to build a menu structure with AutoHotkey.
Jack discusses how his new app QuickLinks was written with a short AutoHotkey script.
Chapter Twenty-two: Tweaking the QuickLinks AutoHotkey Script
A reader's question prompts a look at improving AutoHotkey scripts by adding QuickLinks to the System Tray icon right-click menu.
What if your keyboard doesn't have a Windows key? Here are some simple modifications to the AutoHotkey scripts. Plus compiling AHK scripts into EXE files that run on any Windows computer.

Part V Index to Chapters

A_LoopFileName, Chapter Twenty-one
A_ThisMenu, Chapter Twenty-one
A_ThisMenuItem, Chapter Twenty-one
A_ThisMenuItemPos, Chapter Twenty-one
A_UserName, Chapter NineteenChapter Twenty-one
Adding menu items to System Tray, Chapter Twenty-two
Breaking lines of code, Chapter Nineteen
Change the System Tray icon, Chapter Twenty-two
Compiling AHK scripts, Chapter Twenty-two
Continue commandChapter Twenty-one
Continuing lines of code, Chapter Nineteen
Convert .ahk to .exe utility, Chapter Twenty-two
Displaying program icons,, Chapter Nineteen
EXE, compiling from AHK scripts, Chapter Twenty-two
FileCreateDir commandChapter Twenty-one
Files, hidden and system, Chapter Twenty-one
Folders, looping through files, Chapter Twenty-one
Formatting, GUI, Chapter ElevenChapter Nineteen
Labels, subroutines, Chapter NineteenChapter Twenty-one
Launching Web sites in a browser, Chapter Nineteen
LOOP (files & folders) commandChapter Twenty-one
Loop within a loop, Chapter Twenty-one
Menu, add to System Tray, Chapter Twenty-two
Menu, remove (and add) standard items in System Tray, Chapter Twenty-two
Menu commandChapter TwentyChapter Twenty-oneChapter Twenty-two
Pop-up menu (QuickLinks), Chapter Twenty-one
Properties window, Chapter Nineteen
QuickLinks, add to System Tray, Chapter Twenty-two
QuickLinks AutoHotkey app, Chapter TwentyChapter Twenty-one
Replacing Windows 8 Start Menu, Chapter NineteenChapter Twenty
Return, Chapter Nineteen
Run commandChapter Nineteen
Start Menu, make your own, Chapter Nineteen
Submenu, Chapter Twenty-one
Subroutines, (labels), Chapter NineteenChapter Twenty-one
System Tray, adding right-click menu, Chapter Twenty-two
System Tray, removing (and adding) standard menu items, Chapter Twenty-two
System Tray, change icon, Chapter Twenty-two
Toggle routine, Chapter Twenty-one
Wildcards, Chapter Twenty-one




#SingleInstance, Force
OnExit, OnExit
VarSetCapacity(DEVMODE, 220, 0)
NumPut(220, DEVMODE, 68, "short")   ; dmSize
DllCall("EnumDisplaySettingsW", "ptr", 0, "int", -1, "ptr", &DEVMODE)
width := NumGet(DEVMODE, 172, "uint")
height := NumGet(DEVMODE, 176, "uint")

f11::
n := !n
if n
{
   NumPut(width, DEVMODE, 176, "int")
   NumPut(height, DEVMODE, 172, "int")
   NumPut(DMDO_90 := 1, DEVMODE, 84, "int")   ; dmDisplayOrientation
   DllCall("ChangeDisplaySettingsW", "ptr", &DEVMODE, "uint", 0)
   hHookMouse := DllCall("SetWindowsHookEx", "int", WH_MOUSE_LL := 14, "ptr", RegisterCallback("WH_MOUSE_LL", "Fast"), "ptr", DllCall("GetModuleHandle", "uint", 0, "ptr"), "uint", 0, "ptr")
}
else
   GoSub, RemoveHook
return

OnExit:
RemoveHook:
if hHookMouse
{
   DllCall("UnhookWindowsHookEx", "ptr", hHookMouse)
   NumPut(width, DEVMODE, 172, "int")
   NumPut(height, DEVMODE, 176, "int")
   NumPut(DMDO_DEFAULT := 0, DEVMODE, 84, "int")   ; dmDisplayOrientation
   DllCall("ChangeDisplaySettingsW", "ptr", &DEVMODE, "uint", 0)
   hHookMouse := ""
   if (a_thisLabel = "RemoveHook")
      return
}
ExitApp


WH_MOUSE_LL(nCode, wParam, lParam)
{
   Static lx, ly
   Critical
   if !nCode && (wParam = 0x200)   ; WM_MOUSEMOVE
   {
      mx := NumGet(lParam+0, 0, "int") ; x-coord
      my := NumGet(lParam+0, 4, "int") ; y-coord
      if (lx = "")
         lx := mx
      if (ly = "")
         ly := my
      mx1 := lx - my + ly
      my1 := ly + mx - lx
      DllCall("SetCursorPos", "int", mx1, "int", my1)
      VarSetCapacity(lpPoint, 8)
      DllCall("GetCursorPos", "ptr", &lpPoint)
      lx := NumGet(lpPoint, 0, "int")
      ly := NumGet(lpPoint, 4, "int")
      NumPut(mx1, lParam+0, 0, "int")
      NumPut(my1, lParam+0, 4, "int")
      DllCall("CallNextHookEx", "ptr", 0, "int", nCode, "int", wParam, "ptr", lParam)
      return 1
   }
   else
      return DllCall("CallNextHookEx", "ptr", 0, "int", nCode, "int", wParam, "ptr", lParam) 
}


Комментариев нет:

Отправить комментарий