Create Multiple GUI Pop-Ups in a Single Script (AutoHotkey Scripting)

This AutoHotkey GUI (Graphical User Interface) Trick Builds New GUIs (Graphical User Interfaces) On-the-Fly and in the Same Script without Conflicts

I originally wrote the InstantHotkey.ahk script as a practical demonstration of how to use the Hotkey GUI control. The script’s major downside involves the need to run a new instance of the app for each new Hotkey combination/insertion text pair. Adding the #SingleInstance Off directive solved the problem of loading the same script multiple times, but the System Tray clogged with icons after initiating a number of Instant Hotkeys simultaneously. (I couldn’t just eliminate the System Tray icons (#NoTrayIcon or Menu, Tray, NoIcon) because I could quickly lose track of the various Hotkeys. Plus, eliminating tray icons presents other dangers.)

I combined the script with my master AutoHotkey script by including a Hotkey and the Run command (^!h::Run, InstantHotkey.exe). This avoided the problem of multiple conflicting GUIs in the same script—although it did nothing about the System Tray icon overload.

My recent work inspired me to solve the problem by uniquely naming the GUIs. In the course of writing the new script, I added a number of other useful techniques which I plan to cover in future blogs. Stayed tuned! You might find a few of them quite helpful. Continue reading

Advertisements

Quick Fix for Inserting Color Data into Windows Paint (AutoHotkey Tip)

Auto-Fill Windows Program Data Fields Using RegEx—Plus, Alternative for Pop-up Messages

While the Coloretta Viva script copies pixel colors, transferring codes to Windows Paint gets awkward. This AutoHotkey data filling technique for multiple fields works in any Windows program. Plus, we look at another method for popping up user messages.

I recently highlighted the AutoHotkey Coloretta Viva color picking app at ComputorEdge Software Showcase. As a color matching tool, I consider the script an excellent start. However, I offer a couple of observations. Continue reading

Stuffing More into AutoHotkey Pop-up Menus (AutoHotkey Tip)

Rather Than Increasing the Length of a System Tray Menu, Add Submenus—Plus, How to Use Menu Names (A_ThisMenu) for Conditional Actions

cheeseburgerrecipeWhen I decided to add two more recipes to the cheeseburgerwhiteicon Jack Stuffed Cheeseburger script, I ran into the problem of adding too many items (one for each step in each recipe) to the System Tray right-click menu. In the original, Cheeseburger.ahk script, I only included four steps in the menu (Ingredients, Prepare, Cook, and Serve). However, after inserting the Animal-Style Cheeseburger and the Jack Stuffed Cheeseburger (Animal Style) into the script, the number of recipe increments jumped from four to 18—plus an additional Print Recipe option for each burger. Also, since many of the steps use the same (or similar names), I needed a method for identifying each step with the proper recipe. When increasing the number of AutoHotkey menu options, cumbersome lists of items commonly crop up. You can fix these bloated menus by using submenus. Continue reading

GoTo Command Versus GoSub Command (AutoHotkey Tip)

While the Online Documentation Advises Avoiding the AutoHotkey GoTo Command in Deference to GoSub or a User-Defined Function, You’ll Find Times When GoTo Works Best!

cheeseburgerwhiteicon Not everyone likes their cheeseburger prepared the same way. Some prefer fried onions while others love the crunch of raw condiments. In fact, In-N-Out Burger touts a not-so-secret menu offering cheeseburgers “Animal Style.” The preparation of this option with caramelized onions and mustard fried hamburger significantly changes the cheeseburger experience. That gives us an excuse to add flexibility to our CheeseburgerRecipe.ahk script—first discussed in the blogs “Why AutoHotkey for Chefs and Dieticians?” and “Understanding Label Names and Subroutines (Beginning AutoHotkey Tip).”

Note: I changed the CheeseburgerRecipe.ahk script in a number of ways—a few of which I plan to discuss in future AutoHotkey Tips. For now, I confine myself to highlighting the use of the GoTo command. For specific changes, see the comments at the top of the CheeseburgerRecipe.ahk script.

Adding Options to the Cheeseburger Recipe

I found another recipe at FoodNetwork.com which replicates the In-N-Out Animal-Style Cheeseburger recipe. Copying the same AutoHotkey techniques I used for the Jack Stuffed Cheeseburger, I added the new steps for this recipe to the script. Since the System Tray menu grew too crowded, I implemented submenus for each recipe. (See image below.)

CheeseburgerAnimalStyle
Recipes listed in the System Tray icon right-click menu include submenus for selecting individual steps, then continue displaying succeeding steps unless canceled.

The primary differences between the Jack Stuffed Cheeseburger and the Animal-Style Cheeseburger include caramelizing onions, mixing a special sauce, burgers with no embedded cheese, preparation of the buns, and frying the burgers with mustard. While more involved than the first recipe, the new recipe might satisfy the “Animal” in anyone. But, what if you wanted a Jack Stuffed Cheeseburger Animal Style?

You could write an entirely new recipe for a Jack Stuffed Cheeseburger Animal Style but that would include a great deal of redundancy. By using the AutoHotkey GoTo command, we combine the redundant steps of the two recipes to create a third variation.

CheeseburgerGoTo
Each column represents one recipe subroutine followed by a single Return command at the end. Each box contains the Label name for the location of that individual step within the recipe. After each step, AutoHotkey automatically drops into the Label below since no Return command intervenes until the end of the recipe. The GoTo commands in the third recipe jump to the Label name point (e.g. GoTo, Animal_Onions) in the appropriate recipe subroutine—proceeding as if a totally separate recipe.

For the new Jack Stuffed Animal Style Cheeseburger, the recipe starts at the Label point Stuffed_Animal_Ingredients: which includes the ingredients for the Animal Style Cheeseburger plus the added Jack cheese (for stuffing) and varied meat and cheese amounts. Using the GoTo command, AutoHotkey jumps directly to the Animal_Onions: pointer for caramelizing the onions.

Since the process jumps into the middle of the Animal Style Cheeseburger subroutine, when the Animal Style Cheeseburger – Onions window closes, it automatically drops into the Animal_Sauce: routine. Next, the recipe must GoTo the Jack Stuffed Cheeseburger Label named Prepare: for shaping the burgers with Monterey Jack cheese inside. In order to make this jump decision, AutoHotkey must identify the currently running recipe subroutine: either Animal Style Cheese Burger (no Goto) or Jack Stuffed Animal Style (GoTo).

The initial menu selection tells us which recipe track to follow. The menu name (A_ThisMenu) identifies the Jack Stuffed Animal Style recipe:

If (A_ThisMenu = "StuffedAnimal")
  StuffedAnimal = 1
Else
  StuffedAnimal = 0

Placing this condition into the MessageSetup: subroutine identifies the origin of any mixed-use menu steps. AutoHotkey determines the proper path by checking the value of the StuffedAnimal variable. For example, after the Animal_Sauce: window, the process uses the following check:

If (StuffedAnimal = 1)
  GoTo, Prepare

If running the Jack Stuffed Animal Style sequence (StuffedAnimal = 1), AutoHotkey jumps to the Prepare: point of the Jack Stuffed Cheeseburger routine. Otherwise, the Animal Style Cheeseburger continues dropping through its steps.

This same conditional format creates the jumps from Prepare: to the Animal_Buns: point and from Animal_Buns: to the Stuffed_Animal_Cook: point for the Jack Stuffed Animal Style steps. This process creates a new variation from older recipes without rewriting redundant steps. Often using the GoSub command (for Go Subroutine) works better, but in this situation, GoTo makes the routine act as if it’s one continuous series of steps.

GoTo Versus GoSub

megadeal180goldTo understand the difference between the GoTo command and the GoSub command, know that when a subroutine finishes, the GoSub command returns to the next line in the original calling routine, while the GoTo command does not. In most cases, since it returns to the same spot in the script, you’ll probably find the GoSub command (or a function) more appropriate. But if you know that you don’t want to return to that point, then feel free to use GoTo—but you better know where you plan to end up.

A common usage of GoSub runs the subroutine then returns to the next line after the calling line. For example, I moved the loading of the recipe variables for each step out of the auto-execute section of the script into separate Label subroutines, then replaced each with a single GoSub command. This made the script more readable by greatly reducing the length of the auto-execute section. In place of the code, I inserted the following GoSub command statements:

GoSub, StuffedCheeseburger 
GoSub, AnimalCheeseburger
GoSub, StuffedAnimalCheeseburger

However, using the GoSub command in the mixed recipe scenario for the Jack Stuffed Cheeseburger Animal Style would have caused more problems than it solved. For example, if the GoSub command appeared in place of GoTo, then each call would create a new return point. That means clicking the Cancel button would cause the script to jump to the last GoSub call rather than exiting the thread. In many cases, jumping back would cause unwanted effects (e.g. display an inappropriate step from another recipe). In fact, even running through the entire recipe without canceling would cause an untold number of displays of various steps. After encountering the last Return in the subroutine, the final Return jump executes more GoSub commands—each creating an additional Return point. The GoTo command keeps it clean, allowing an exit with any Return encountered in any recipe sequence. To the user, each recipe (including the mixed) looks like a continuous set of steps.

While probably best avoided if GoSub or a function can do the job, the GoTo command works well in scripts emulating flow charts and plays an important role in decision trees. In those special situations, knowing where you are (and where you’re going) may be more important than where you’ve been.

Printing with AutoHotkey Made Simple (AutoHotkey Tip)

While Other Techniques Exist for Printing Directly from AutoHotkey, Make It Easy by Using Print Drivers from Other Programs

When I first considered printing from the cheeseburger recipe script, I didn’t realize how complicated printing from AutoHotkey can get. With any printing, a number of factors come into play. First, each printer model uses particular print drivers. Second, the format of the document affects the output and drivers. Third, you may need to choose from multiple printers.

While I found a number of solutions, they tended to involve more advanced techniques using DllCall(), print spoolers, and other enigmatic code. This plays well for anyone comfortable with Windows’ inner workings and hidden mechanisms but gets too complicated for the average AutoHotkey user. I always look for the simplest (and sometimes the most effective) method to get things done.

The problems mentioned above (print drivers, file formats, and multiple printers) never go away. AutoHotkey scripts need tailoring to specific setups and circumstance. So why reinvent the wheel? Most Windows programs solved these printing problems long ago. By default, CTRL+P opens the print dialog in Windows applications, but if you only want to print directly to the default printer without the dialog, then the Windows Command Prompt or the Run dialog box (WIN+R or microsoft_key+R) may be your best bet. In most situations, you can take advantage of those prepackaged software solutions.

Using Windows Program Command Line Capabilities

Windows programs allow launching from the Command Prompt window. As long as the right parameters exist and you include them, you can take advantage of the apps printing capability. Since most software matches a particular file type (e.g. TXT for Notepad, JPG or GIF for Windows Paint, PDF for Foxit Reader), you can match your printing routines to the file type through the external software. Thus, the application does all the print formatting work for you.

In AutoHotkey, the AutoHotkey Run command serves the same purpose as the Run (WIN+R or microsoft_key+R) dialog box in Windows.

Using Windows Notepad for Printing Text

One of the simplest methods for printing text in AutoHotkey uses the ubiquitous Windows Notepad app. As a no-frills text processor, it can format and print any text file. Best of all, Notepad can print the text file through the AutoHotkey Run command.

Open a text file in Notepad through AutoHotkey with simply:

Run, Notepad.exe FileName.txt

To silently print (no print dialog), add the print switch (/p):

Run, Notepad.exe /p FileName.txt

Using the /p switch, AutoHotkey launches Notepad running the built-in print drivers to format and send the text file to the default printer. (A Notepad window opens, loads the text file, sends it to the printer, then immediately closes—possibly so fast that you miss it.) For example, AutoHotkey can use Notepad to print the “Jack Stuffed Cheeseburger” recipe.

AddPrintMenuItemPrinting the Cheeseburger Recipe

Not everyone keeps a computer in their kitchen. Even then, a recipe printed on a piece a paper offers easy access to ingredients and instructions without putting a machine in the kitchen—at risk to spills and other culinary disasters. Plus, carrying a printed list of ingredients to the grocery store often proves advantageous—even over a smartphone.

To add the print feature to the CheeseBurgerRecipe.ahk script, I first use the Menu command to insert a new Print All menu item—as shown at the right:

Menu, tray, add, Print All, Print

then, I write the accompanying Label subroutine Print:

Print:
  FileDelete, RecipePrint.txt
  FileAppend , % "Jack Stuffed Cheeseburgers`r`r" 
    . Ingredients . "`r`r" . Mix . "`r`r" . Cook 
    . "`r`r" . Serve, RecipePrint.txt
  Run, Notepad.exe -p RecipePrint.txt
Return

(For display purposes, the FileAppend line of code uses the force expression operator (%) and line continuation techniques to wrap the single line of code into multiple lines.)

First, just in case a residue file from a previous print operation exists, the FileDelete command executes. (This FileDelete could just as easily appear after the Run command line.) Next, the FileAppend command adds the text to a temporary file (RecipePrint.txt), then, using the Run command, prints the file through Windows Notepad.

Note: I also added an option to print individual sections of the recipe (e.g. only the list of ingredients) to each MsgBox section of the recipe using the built-in Help button and a PrintItem() function. A more complex approach, I implemented techniques discussed in the “Tips for Optimizing the Standard AutoHotkey Message Box (MsgBox) Command” blog. I’ll leave this discussion for another time.

Windows Program Switches

RunDialogBoxMany programs include parameters or switches to perform specific functions either through the Windows Command Prompt window or the Run dialog box—shown at right. Those commands and switches work the same way with the AutoHotkey Run command. Not all programs offer command line switches, but enough free programs exist to allow the printing of almost any type of file via AutoHotkey. A little investigation answers any questions.

A search of the Web for Windows program switches (normally a slash / or dash – followed by one or more characters) usually yields the parameters needed for printing  (e.g. /p or -p) in conjunction with the Run command. Some programs also offer switches for selecting the target printer (e.g. /t or /pt). However, many applications don’t offer any command line print options at all. Therefore, you must write your scripts to use the software application which works best for your purposes.

Notepad Versus Wordpad for Printing

While Notepad works great for text, Windows Wordpad offers similar results. Notepad might respond a little quicker, but Wordpad prints more file formats:

Run, write /p "c:\AutoHotkey\Spicy Beef Minestrone.docx"

In the above line of code, AutoHotkey instructs Wordpad to load, print the Microsoft Word DOCX file, then close. (Tip: The term “Wordpad” works in place of “write” as the program source.) Generally, AutoHotkey prints any format available for reading and saving files within a specific software package. In the case of Wordpad, AutoHotkey can also send to a printer the free OpenOffice (LibreOffice) document format (ODT), as well as, the Rich Text Format (RTF).

Note: Not all programs accept command line switches. Therefore, your favorite software might not work for printing directly from AutoHotkey.

*          *          *

For more information about LibreOffice, get Rob Spahitz’s book Getting Started with OpenOffice (LibreOffice): The Free Replacement for Microsoft Office at Amazon.com.

*          *          *

Printing Graphics Files

Suppose you want to print any graphic file such as BMP, JPG, PNG, GIF, or TIF? You might find a number of options, but you need to test them with the AutoHotkey Run command.

I tested the Microsoft Paint program, but, for me, regardless of efforts to change default settings, the printer always used the landscape print mode and expanded the image to fill the page. I moved over to my favorite free image viewer, IrfanView, achieving much better results. But even then I needed to tinker with the print setup in the program.

Tip: For most programs, the AutoHotkey Run command with a print switch uses the default print setup for the program. If you don’t get what you want (e.g. landscape versus portrait mode), open the file in the program, change the print setup, and print. Then close the program. I found in a number of Windows programs that this resets the default printing mode for AutoHotkey. Generally, the last print setup used in a Windows program gets saved as the default.

I found a list of the IrfanView print parameters on the Web. For IrfanView, be sure to include the complete path to the program:

Run, C:\Program Files (x86)\IrfanView\i_view32.exe "C:\AutoHotkey\Cheeseburger Cook.png" /print

If any spaces occur in the print file’s name or path, be sure to enclose it in quotation marks. The Run command does not require double quotes around the command program path and filename—even if spaces occur within it.

Notice that for IrfanView the print switch includes the entire word /print. IrfanView should work for most graphic file formats but test it to be sure.

Printing More File Formats

While many Windows programs don’t include print run parameters, I found this list of common command line switches for popular software. You may find your favorite programs here.

For PDF files, I use the free Foxit Reader. It turns out that FoxitReader also does a great job for printing PDF files through AutoHotkey. From the above list of common command line switches:

Print a PDF file silently to the default printer:

“FoxitReader.exe” /p PdfFile

Print a PDF file silently to an alternative printer:

“FoxitReader.exe” /t PdfFile PrinterName

I simply added the following to an AutoHotkey script:

Run, FoxitReader.exe /p C:\AutoHotkey\PortableDoc.pdf

AutoHotkey prints the PDF file through the Foxit Reader program.

Notice that the command works without including the complete path to the file Foxit Reader.exe:

C:\Program Files (x86)\Foxit Software\Foxit Reader\Foxit Reader.exe

That means that during installation either the program was added to the system or user path where Windows automatically searches or a shortcut was added to the Windows Registry, such as:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\foxitreader.exe

In many cases, a shortened program name won’t work with Run command. For example, IrfanView requires the full path in the Run command. That means IrfanView did not get added to a system or user path nor the Registry during installation.

As mentioned in the tip above, I found that changing and saving the print settings in Foxit Reader fixed any formatting problems when printing from AutoHotkey.

Expanding AutoHotkey Print Opportunities

Many other file formats exist which demand different print drivers. Rather than finding a program for each format, turning to one free software program with drivers for multiple formats makes things easier. The free LibreOffice suite of programs offers print drivers for numerous file formats including Microsoft Word,  Excel, and PowerPoint, plus, all the OpenOffice formats (ODT, ODS, etc.). (For an introduction to OpenOffice/LibreOffice, see Rob Spahitz book Getting Started with OpenOffice (LibreOffice): The Free Replacement for Microsoft Office.)

*          *          *

For more information about LibreOffice, get Rob Spahitz’s book Getting Started with OpenOffice (LibreOffice): The Free Replacement for Microsoft Office at Amazon.com.

*          *          *

Although different command EXE files exist for each package in the suite, LibreOffice allows one main path for all supported print formats with one soffice.exe command file:

Run, C:\Program Files (x86)\LibreOffice 4\program\soffice.exe -p "c:\AutoHotkey\Spicy Beef Minestrone.docx"

This AutoHotkey Run command prints a Microsoft Word file. (Note that the LibreOffice print switch uses a dash rather than a forward slash.)

I found soffice.exe in the App Paths section of the Windows Registry discussed above. That means we can shorten the Run command line by eliminating the program path:

Run, soffice.exe -p ExcelFile.xls

This line prints a Microsoft Excel file using LibreOffice print drivers.

If you need to print other file formats, find software which both supports the file type and allows printing from the Windows Run dialog box.

While other methods for printing from AutoHotkey exist, I found it easy to use the print drivers in other (usually free) software packages.

*          *          *

Like anybody else, I have expenses and a need to make ends meet. As Jack’s AutoHotkey Blog increases in popularity, coding the test scripts and writing the blogs takes up more of my time. That means I’ve less time to pursue other income earning opportunities. I don’t plan to ever move Jack’s AutoHotkey Blog behind a paywall, but if you think my efforts are worth a bit of your hard-earned cash, then you can offer a token of your appreciation by purchasing one or two of my AutoHotkey books. You may not need the references yourself, but you might know someone who can benefit from one or two of them.

Thank you,

jack

Understanding Label Names and Subroutines (Beginning AutoHotkey Tip)

Once You Know How AutoHotkey Label Names Work, You Can Add More Tricks to Your Bag of AutoHotkey Skills

cheeseburger-ingredientsWhile in the past I often used the terms AutoHotkey Label and subroutine interchangeably, that’s not exactly accurate—although the two terms maintain a close relationship. Misunderstanding how Label names work can be a source of errors for new AutoHotkey script writers. However, knowing the differences between what constitutes a Label and a subroutine opens up new scripting opportunities. The CheeseBurgerRecipe.ahk script uses little-known Label behavior to either walk through all the steps or jump to individual sections of the recipe for a “Jack Stuffed Cheeseburger.” Continue reading

Why AutoHotkey for Chefs and Dieticians?

cheeseburgerwhiteicon While You Don’t Often See Television Chefs Using Computers, AutoHotkey Offers Guidance When Cooking “Jack Stuffed Cheeseburgers” at Home

*          *          *

While I came up with a pretty cool barebones recipe script for this AutoHotkey blog, I’m not sure how well computers and cooking mix. From what I’ve seen, professional chefs don’t have much time to mess with technology—except for possibly writing cookbooks—in which case, I would refer them to “Why AutoHotkey for Writers, Bloggers, and Editors?.”

*          *          *

cheeseburgercartoon

Using a computer while cooking presents a challenging task. Although looking up a recipe on a smartphone works great, poking at the device with fingers covered in cookie dough proves impractical. Ideally, any kitchen machine is lightweight and stands upright on its own.

Although a little pricey, the Microsoft Surface Pro (or another less expensive Windows ultralight laptop computer) might do the job. Large enough to read the screen, yet easy to move around a cooking area, these computers help any budding chef or dietician who needs to check recipes—as long as no one dumps boiling water on the keyboard. For size and convenience, finding equipment more practical than a lightweight laptop proves difficult. Continue reading