MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro...

24
Benthien 2017 1 MACRO INTRODUCTION Wikipedia’s definition of a macro is approximately as follows: A macro, short for "macroinstruction", in computer science is a rule or pattern that specifies how a certain input sequence, often a sequence of characters, should be mapped to a replacement output sequence, according to a defined procedure. If you search the Internet, you will find quite a lot of other definitions and different views on macros and macro programming. What we examine here however, is how to use macros as a powerful tool and simplified programming language, which allows us to automate tasks and add functionality to other applications. Do not worry about the programming aspect for now, you will be able to record basic macros, with little or no need for actual programming, though more advanced task will require a bit of coding, most of the code will be auto-generated or can be found on the Internet. USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even feature built-in Visual Basic tools for creating macros. In the following, we will focus on two external and separate all-purpose programs: 1. TinyTask. - A small program one can use to record simple macros without the use of code. Good for quick and dirty tasks you only need done once or twice. 2. Autohotkey. - A flexible program, which, using AutoScriptWriter, will both record your macro and generate Autohotkey code at the same time. That means, one records the steps to execute, then modify and loop the code as needed and afterwards it is possible to reuse, or even compile the code as a standalone “.exe” file and run the macro reliably on other computers without Autohotkey installed. WHY DO I NEED TO LEARN THIS? In your career as an IT professional, you will undoubtedly encounter many repetitive tasks. Learning basic macro programming will enable you to automate many of the more tedious aspects of your job. Thereby freeing your time, sparing your company’s resources, make the automated tasks less error prone and direct your focus to the tasks actually in need of human attention. People are quick to use the phrase “Work smarter, not harder”, but few show you how it is done. This introduction will do just that. Many companies outsource repetitive tasks, software testing and manual data entry, like password resets or user administration. E.g. the creation and termination of users to countries where labor costs are low but what is the smartest solution; Outsource a task and rely on an external company to get it done, for a low monthly fee, or automate it and get it done for free without the possibility of human errors, only relying on yourself?

Transcript of MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro...

Page 1: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

1

MACRO INTRODUCTION

Wikipedia’s definition of a macro is approximately as follows:

A macro, short for "macroinstruction", in computer science is a rule or pattern that specifies how a certain input

sequence, often a sequence of characters, should be mapped to a replacement output sequence, according to a defined

procedure.

If you search the Internet, you will find quite a lot of other definitions and different views on macros and macro

programming.

What we examine here however, is how to use macros as a powerful tool and simplified programming language, which

allows us to automate tasks and add functionality to other applications.

Do not worry about the programming aspect for now, you will be able to record basic macros, with little or no need for

actual programming, though more advanced task will require a bit of coding, most of the code will be auto-generated or

can be found on the Internet.

USING MACROS

There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even feature built-in Visual Basic tools for creating macros. In the following, we will focus on two external and separate all-purpose programs:

1. TinyTask.

- A small program one can use to record simple macros without the use of code. Good for quick and dirty tasks you only need done once or twice.

2. Autohotkey.

- A flexible program, which, using AutoScriptWriter, will both record your macro and generate Autohotkey code at the same time. That means, one records the steps to execute, then modify and loop the code as needed and afterwards it is possible to reuse, or even compile the code as a standalone “.exe” file and run the macro reliably on other computers without Autohotkey installed.

WHY DO I NEED TO LEARN THIS?

In your career as an IT professional, you will undoubtedly encounter many repetitive tasks. Learning basic macro

programming will enable you to automate many of the more tedious aspects of your job. Thereby freeing your time,

sparing your company’s resources, make the automated tasks less error prone and direct your focus to the tasks actually

in need of human attention. People are quick to use the phrase “Work smarter, not harder”, but few show you how it is

done. This introduction will do just that.

Many companies outsource repetitive tasks, software testing and manual data entry, like password resets or user administration. E.g. the creation and termination of users to countries where labor costs are low but what is the smartest solution; Outsource a task and rely on an external company to get it done, for a low monthly fee, or

automate it and get it done for free without the possibility of human errors, only relying on yourself?

Page 2: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

2

TABLE OF CONTENT

Macro introduction .................................................................................................................................................................... 1

Using Macros ......................................................................................................................................................................... 1

Why do I need to learn this? ................................................................................................................................................. 1

Installing the programs .............................................................................................................................................................. 4

TinyTask ................................................................................................................................................................................. 4

Autohotkey ............................................................................................................................................................................ 4

Best Practice .............................................................................................................................................................................. 4

Using TinyTask ........................................................................................................................................................................... 5

The user interface ................................................................................................................................................................. 5

Automating a manual data entry task ................................................................................................................................... 5

The Task ............................................................................................................................................................................ 5

Setting up .......................................................................................................................................................................... 5

Considering the task ......................................................................................................................................................... 7

Recording the Macro ........................................................................................................................................................ 7

Conclusion TinyTask .............................................................................................................................................................. 8

Using Autohotkey ...................................................................................................................................................................... 8

Editing scripts ........................................................................................................................................................................ 8

The AutoScriptWriter user interface ..................................................................................................................................... 9

Automating a manual data entry task ................................................................................................................................... 9

Considering the task ......................................................................................................................................................... 9

Recording the Macro ........................................................................................................................................................ 9

Deconstructing the code ................................................................................................................................................. 11

Testing the script ............................................................................................................................................................. 12

The script......................................................................................................................................................................... 13

Page 3: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

3

Creating some hotkeys ........................................................................................................................................................ 14

Creating a Script .............................................................................................................................................................. 14

Defining your first hotkey ............................................................................................................................................... 15

Defining a shortcutkey to open a program ..................................................................................................................... 17

Speeding up your Google searches ................................................................................................................................. 17

Hotstring replacement ........................................................................................................................................................ 18

Combining shortcuts with dataentry and enable pause ..................................................................................................... 19

Making your script run when Windows start ...................................................................................................................... 19

Conclusion Autohotkey ....................................................................................................................................................... 20

Additional shortcuts and further reading ............................................................................................................................ 20

Tools ................................................................................................................................................................................ 20

Training Exercises ................................................................................................................................................................ 21

Page 4: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

4

INSTALLING THE PROGRAMS

TINYTASK

TinyTask consist of a single “.exe” file, tinytask.exe. No installation is necessary.

Head to http://www.vtaskstudio.com/support.php and download the latest version of TinyTask.

AUTOHOTKEY

Autohotkey needs to be installed. To use the recorder AutoScriptWriter, you will also need to download a separate file

and drag the AutoScriptWriter-folder to your installation directory.

First go to https://autohotkey.com/download/, download the Autohotkey installer and install the program.

Howtogeek.com has written an installation guide. Find it here: http://www.howtogeek.com/56481/the-beginners-guide-

to-using-an-autohotkey-script/.

Next, we will need to grab AutoScriptWriter from an old installation file, since it is not included in the newer versions of

the Autohotkey installation. Download and open AutoHotkey.zip from this link:

https://web.archive.org/web/20150908182356/http:/www.autohotkey.com/download/AutoHotkey.zip.

Now drag the folder AutoScriptWriter to your Autohotkey installation directory, which is most likely located in

%programfiles%\Autohotkey.

BEST PRACTICE

When recording a macro, it is best not to rely too much on mouse clicks, since at different screen resolutions the

coordinate recorded for the mouse click might vary and this can lead to unexpected results. Likewise, if you for instance

click on an OK-button in a popup window, there is no guarantee that the window will pop up in exactly the same place the

next time, even if you stay at the same desktop resolution. And finally, if you compile your script to an “.exe” file and send

it to another PC, there might be subtle differences in themes, the size of task- and menu bars, language of the OS etc.,

which is impossible to account for, when recording the macro.

When recording macros, try to rely on shortcut keys. For instance, if you need to change between two programs use alt +

tab instead of clicking on the program in the taskbar. Use your arrow keys to position the cursor and line up the programs

you need to use before recording. For instance, in newer versions of Windows, you can use win + left arrow to snap a

window to the left side of the screen and select the program you want on the right side.

Page 5: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

5

USING TINYTASK

THE USER INTERFACE

When you first open TinyTask, you are presented with a simple user interface, as seen in Figure 1.

You have the following buttons: Open, Save, Record, Play, Compile and Options.

Figure 1. TinyTask

Open – Opens any recorded macros, recorded with TinyTask, with the filetype extension “.rec”.

Save – If you have recorded a macro, you can save it for later use by hitting Save.

Record – To record a new macro, press Record or ctrl+shift+alt+r.

Play – To playback a newly recorded or loaded macro, press Play or ctrl+shift+alt+p.

Compile – Save your macro as an “.exe” file.

Options – Display options, set repeat count and playback speed etc. here.

Since TinyTask does not generate code, it is best used for relatively simple data entry and tasks you only need to run once

or twice.

AUTOMATING A MANUAL DATA ENTRY TASK

THE TASK

Let us say you need to create some logins for a list of new users, in a web based system.

Normally, you would receive a list of names and emails in a spreadsheet from the HR department and would need to copy

each name, surname and email individually to specific boxes in a web form. Additionally, check off a few boxes to define

the rights and permission of each user. Finally, you would hit an Apply-button to confirm. Let us see if we can get TinyTask

to do this automatically.

SETTING UP

1. Download this:

http://benthien.dk/Docs/Names.xlsx

Open the file in Excel and maximize the window.

2. Now open this:

http://benthien.dk/Docs/CreateUsers.htm

3. With Excel open, press win + arrow left.

Now select the web form as your second window, so that your screen looks like this:

Page 6: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

6

4. Look at the web form, as you can see, there is a password field. Since no passwords were included in the

spreadsheet, you can choose one of the following options:

- Either you can give all users the same initial password, which is not very safe.

- Or you could enter a password manually for each user, which would be time consuming and therefore defeat

the whole purpose of trying to save us some time.

- A more favorable option but a less optimal solution would be to use an online random password generator,

considering most people use MS Excel as their spreadsheet application of choice.

- If you use MS Excel, we can get the spreadsheet itself to generate some random passwords by using a

Function.

Let us examine the last option, since it is by far that fastest of the four.

GENERATING A RANDOM PASSWORD IN EXCEL

a. If you are using the English version of Excel Click the cell D1, select the Function box and paste this:

=CHAR(RANDBETWEEN(65;90))&RANDBETWEEN(0;9)&CHAR(RANDBETWEEN(65;90))&RANDBETWEEN(0

;9)&CHAR(RANDBETWEEN(65;90))&RANDBETWEEN(0;9)&CHAR(RANDBETWEEN(65;90))&RANDBETWEE

N(0;9)

b. Use this Function instead, if you are using the Danish version of Excel:

=TEGN(SLUMPMELLEM(65;90))&SLUMPMELLEM(0;9)&TEGN(SLUMPMELLEM(65;90))&SLUMPMELLEM(0

;9)&TEGN(SLUMPMELLEM(65;90))&SLUMPMELLEM(0;9)&TEGN(SLUMPMELLEM(65;90))&SLUMPMELLE

M(0;9)

c. Now copy the function to all cells between D1 – D20. You can do so by grabbing the selector box in the

lower right corner of the cell and pulling down to D20.

Page 7: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

7

5. Now start TinyTask.

CONSIDERING THE TASK

It is always a good idea to examine and plan all the steps needed to run the task before actually recording the macro.

Therefore, do not hit record just yet but do the following and evaluate the steps as you go. It might be a good idea, if you

do not have a multi monitor setup to print these instructions:

1. First off, you will need to make sure your spreadsheet window is active.

2. Secondly, you need the user’s first name, position the selector box over the first name (A1) and then copy the

name by hitting ctrl + c.

3. Then click the web forms title bar if the “Firstname” textbox is not already active. You will need to left click on

the textbox to activate it. Paste the name by hitting ctrl + v and jump to the “Surname” box by hitting tab.

4. Activate the spreadsheet again by clicking its title bar.

5. Then hit arrow right to select the user’s surname (B1), copy the name by hitting ctrl + c.

6. Activate the web form by clicking the title bar. The “Surname” box should be activated as per step 3.

7. Paste the surname by using ctrl + v and hit tab to activate the “Email” box.

8. Repeat step 4 to 7 to copy the user’s email and password to the web form.

9. When you have pasted the password and hit tab, you will see the first checkbox being highlighted. Let us ‘Grant

access A’ by hitting space and then tab. Do the same to check access B and C.

10. Now hit tab to highlight the “Submit” button, press enter to submit the form and enter to press the “OK” button.

11. Finally hit tab to activate the “Firstname” textbox again and click the spreadsheet title bar and select the next

user’s first name by hitting home and then arrow down.

NOTE!

You might be wondering, after reading the best practice section, why we use the mouse for some of the steps.

The explanation is that since TinyTask does not generate any code, we cannot modify and control the wait times of the

commands. That means the alt + tab command could be executed too fast for the OS to handle, which could result in a

tabulator sent in the active program instead of it changing to the other program as expected. To make matters worse, it

could then send the alt command in combination with the next command, for instance alt + ctrl + c instead of just ctrl + c

and still be in the wrong program. This makes the script prone to errors. That is why we only use Tinytask for quick non-

repeat jobs since it is too dependent on stuff like the OS response time to make it a viable tool for larger jobs running at a

regular variable.

RECORDING THE MACRO

Now we are ready to record our first macro.

Simply hit record by hitting ctrl + alt + shift + r and follow steps 1 to 11. Note that in step 2 the second user’s first name

should already be active, so no clicking the mouse to select the name this time.

When you get to the last step, hit record, ctrl + alt + shift + r once more to stop the recording.

Now you can hit play by pressing ctrl + alt + shift + p, and hopefully, if you followed the steps correctly, you will see the

fruits of your labour. If the macro did what you expected it to, you can go to options in TinyTask and set the repeat count

Page 8: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

8

to 17 and “Play Speed: Fast” before hitting play.

If the macro did not act as expected, do not worry, sometimes you will need to adjust the steps a little bit to make it run.

Running a TinyTask macro can vary from PC to PC, so on one PC you might need to record an alt+ tab instead of a mouse

click on the taskbar, or vice versa. Just note that using a mouse to select your input data for copying is a bad idea. It makes

it difficult to loop your macro because mouse coordinates are hard coded. For the same reasons, it is a good idea to test

the macro at least once before you set the repeat count and go grab a cup of coffee.

CONCLUSION TINYTASK

Congratulations on setting up your first macro, once you get the hang of it, it should not take more than a few minutes to

set up a macro for doing similar tasks. Consider the time you will save doing so; if you get a list of a hundred users, you can

easily save an hour and your sanity in the process.

The biggest drawback, using TinyTask, is that when you record something, you cannot edit a step, meaning that if you do

something wrong in step 7 for instance, you will need to rerecord the entire macro from scratch.

USING AUTOHOTKEY

EDITING SCRIPTS

After installing Autohotkey, you can create new Autohotkey script files, by right clicking in windows explorer or on your

desktop, selecting New -> AutoHotkey Script. Basically an Autohotkey script file is just a .txt file renamed to .ahk and that

means you can edit the scripts with Notepad or Notepad++. Notepad++ can even syntax highlight and autocomplete your

commands if you install Autohotkey as a custom language and download the Auto-Completion plugin. Both are nice

features to have but not strictly necessary for this guide.

You can also create a new script using AutoScriptWriter. As mentioned earlier the AutoScriptWriter.exe should be located

in "%programfiles%\Autohotkey\AutoScriptWriter\AutoScriptWriter.exe".

Page 9: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

9

THE AUTOSCRIPTWRITER USER INTERFACE

When opening AutoScriptWriter, you will see a rather empty window at first

that will change as we record our script.

Examining the interface, you have the following buttons:

A Record Monitors your actions and subsequently writes an

Autohotkey script.

Window Text The ScriptWriter will harvest text from the

window you are interacting with to help identify it

upon replaying the script. Text does not always

need to be monitored if window titles change. In some install wizards the window title remains

the same, so Window Text would be useful in that instance.

Record Mouse This button indicates if the ScriptWriter will record mouse clicks, as well as capture keystrokes.

Record and Shrink Will shrink the AutoScriptWriter window when A Record is clicked, essentially getting it out of

the way during record. Note that leaving this enabled when recording might cause the need to

press the Stop button a few times, when you want your recording to end.

Clean Does not do anything at present, the button is left for a future build.

Save Saves your script.

Exit Exits the program, without saving.

At the top you will find a Run line, put a program or command in here, if you wish it to run at the start of you script, if you

for instance wants notepad to run, you would type notepad and hit A Record and notepad would pop up, exactly like any

run command you would put in the Windows run box (win + r).

AUTOMATING A MANUAL DATA ENTRY TASK

CONSIDERING THE TASK

We will be using Autohotkey to automate the same task as above to demonstrate the differences between TinyTask and

Autohotkey. AutoScriptWriter will record our code as we go, so we do not need to exercise quite the same carefulness

when recording, because we will be able to edit the code once we have recorded our macro.

RECORDING THE MACRO

Set up the windows, like we did above.

And as you did before, print the instructions below if you only have one monitor.

Page 10: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

10

Open AutoScriptWriter, leave it at default settings and hit A Record. The stop button will show in the top left corner of

your screen indicating you are recording.

1. Activate the spreadsheet by left clicking the title bar.

2. Position the selector box over the first name (A1) by left clicking it and then copy it by hitting ctrl + c.

3. Click the web forms title bar, if the “Firstname” textbox is not active, left click on it, then paste it with ctrl + v,

jump to the “Surname” box by hitting tab.

4. Activate the spreadsheet again by clicking its title bar.

5. Then hit arrow right to select the users surname (B1), copy the name by hitting ctrl + c.

6. Activate the web form by clicking the title bar, the “Surname” box should be activated as per step 3.

7. Paste the surname, by using ctrl + v and hit tab to activate the “Email” box.

8. Repeat step 4 to 7 to copy the users email and password to the web form.

9. When you have pasted the password and hit tab, you will see the first checkbox being highlighted. Let us grant

access A by hitting space and then tab, repeat for access B and C.

10. Now hit tab to highlight the “Submit” button, hit enter to submit the form, hit enter to press the “OK” button.

11. Hit tab to activate the “Firstname” textbox again and click the spreadsheet title bar and select the next users first

name by hitting home and then arrow down.

12. Finally click the Stop button. You should now have code that looks like this:

Depending on which browser and spreadsheet application you use and what language your OS is in, the names of the

windows might vary a bit. As a user of multiple computers in different OS languages, I recommend you take this into

account when running a script on another PC but for now disregard any name inconsistencies.

Save your script and open it with notepad.

Page 11: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

11

DECONSTRUCTING THE CODE

Examining the three first lines of code you will see something like this:

WinWait, Names.xlsx [Skrivebeskyttet] - Excel,

IfWinNotActive, Names.xlsx [Skrivebeskyttet] - Excel, , WinActivate, Names.xlsx [Skrivebeskyttet] - Excel,

WinWaitActive, Names.xlsx [Skrivebeskyttet] - Excel,

WinWait

Waits until the specified window exists.

IfWinNotActive

Checks if the specified window exists and is currently active (foremost). If it is, WinActive() returns its Unique ID (HWND).

WinWaitActive

Waits until the specified window is active.

So basically the three lines will check if your spreadsheet is active and if not activate it.

Looking to the next line you will see:

MouseClick, left, 427, 7

The MouseClick command will send a click of your mouse or a turn of the mouse wheel to the coordinates specified in the

end of the command. In this case it will left click the coordinates 427, 7 in your active window, 0,0 being the top left of

said window.

But since we only clicked the window to activate it and it recorded the three first lines which activates the spreadsheet,

we no longer need the MouseClick command, so delete this line.

Moving on to the next line we have:

Sleep, 100

The Sleep command waits the amount of milliseconds specified after the comma. Leave that in for now to give the

spreadsheet application some time to react.

Then we have:

MouseClick, left, 68, 229

Sleep, 100

This is where we selected the A1 cell with the mouse in step 2. We do not want the script to do this every time it runs,

instead we will use the arrow keys and home key to navigate the cells, so delete these two lines.

Send, {CTRLDOWN}c{CTRLUP}

The Send command, will send keystrokes to the active window, this line holds down the ctrl key, sends an “c” and then

Page 12: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

12

releases ctrl.

Now the next four lines:

WinWait, Create new user – Google Chrome,

IfWinNotActive, Create new user – Google Chrome, , WinActivate, Create new user – Google Chrome,

WinWaitActive, Create new user – Google Chrome,

MouseClick, left, 762, 25

These lines activate the “Create New User” web form and as you can see I use Google Chrome. Like before we can remove

the unneeded MouseClick command. Actually we do not need the mouse click command at all, so go ahead and remove

all instances of it from the rest of the script, remember to delete the whole line the command is on.

TESTING THE SCRIPT

Now it is time for a test run, save your script and run it.

As you can see your AHK script runs somewhat faster that your TinyTask script, this is partly because it is not dependent

on moving the mouse. This script is also a lot more stable because it activates named windows, instead of just relying on

clicking the title bars. The script disregard things like which zoom level your browser is currently in, what your desktop

resolution is, etc., it only considers whether the two window names are consistent with what is in the script. If you use the

same browser and OS language as when you recorded the macro, the script will run. You can even right click the script and

select “Compile Script” to make the script executable on other PCs without Autohotkey, if you use the same browser and

OS language on the other PC.

When the script finishes its first run successfully, we only need to loop the code, so we do not need to run it 19

consecutive times manually.

This is done by adding:

loop, 19

{

To the top of the script and:

}

To the end.

Page 13: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

13

THE SCRIPT

Now your script should look something like this:

loop, 19

{

WinWait, Names.xlsx [Skrivebeskyttet] - Excel,

IfWinNotActive, Names.xlsx [Skrivebeskyttet] - Excel, , WinActivate, Names.xlsx [Skrivebeskyttet] - Excel,

WinWaitActive, Names.xlsx [Skrivebeskyttet] - Excel,

Send, {CTRLDOWN}c{CTRLUP}

WinWait, Create new user – Google Chrome,

IfWinNotActive, Create new user – Google Chrome, , WinActivate, Create new user – Google Chrome,

WinWaitActive, Create new user – Google Chrome,

Send, {TAB}{CTRLDOWN}v{CTRLUP}{TAB}

WinWait, Names.xlsx [Skrivebeskyttet] - Excel,

IfWinNotActive, Names.xlsx [Skrivebeskyttet] - Excel, , WinActivate, Names.xlsx [Skrivebeskyttet] - Excel,

WinWaitActive, Names.xlsx [Skrivebeskyttet] - Excel,

Send, {RIGHT}{CTRLDOWN}c{CTRLUP}

WinWait, Create new user – Google Chrome,

IfWinNotActive, Create new user – Google Chrome, , WinActivate, Create new user – Google Chrome,

WinWaitActive, Create new user – Google Chrome,

Send, {CTRLDOWN}v{CTRLUP}{TAB}

WinWait, Names.xlsx [Skrivebeskyttet] - Excel,

IfWinNotActive, Names.xlsx [Skrivebeskyttet] - Excel, , WinActivate, Names.xlsx [Skrivebeskyttet] - Excel,

WinWaitActive, Names.xlsx [Skrivebeskyttet] - Excel,

Send, {RIGHT}{CTRLDOWN}c{CTRLUP}

WinWait, Create new user – Google Chrome,

IfWinNotActive, Create new user – Google Chrome, , WinActivate, Create new user – Google Chrome,

WinWaitActive, Create new user – Google Chrome,

Send, {CTRLDOWN}v{CTRLUP}{TAB}

WinWait, Names.xlsx [Skrivebeskyttet] - Excel,

IfWinNotActive, Names.xlsx [Skrivebeskyttet] - Excel, , WinActivate, Names.xlsx [Skrivebeskyttet] - Excel,

WinWaitActive, Names.xlsx [Skrivebeskyttet] - Excel,

Send, {RIGHT}{CTRLDOWN}c{CTRLUP}

WinWait, Create new user – Google Chrome,

IfWinNotActive, Create new user – Google Chrome, , WinActivate, Create new user – Google Chrome,

WinWaitActive, Create new user – Google Chrome,

Send, {CTRLDOWN}v{CTRLUP}{TAB}{SPACE}{TAB}{SPACE}{TAB}{SPACE}{TAB}{ENTER}{ENTER}

WinWait, Names.xlsx [Skrivebeskyttet] - Excel,

IfWinNotActive, Names.xlsx [Skrivebeskyttet] - Excel, , WinActivate, Names.xlsx [Skrivebeskyttet] - Excel,

WinWaitActive, Names.xlsx [Skrivebeskyttet] - Excel,

Page 14: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

14

Send, {HOME}{DOWN}

}

Go ahead and run it and wave goodbye to a future of you doing repetitive things manually.

CREATING SOME HOTKEYS

Automating manual data entry is nice skill to have, Autohotkey though is a versatile tool and can be used for much more

than simple data entry. For example, if you really want to speed up your daily tasks, an Autohotkey script can do pretty

much anything at a push of a button, so let us create some custom hotkeys.

You might be familiar with some of the built-in Windows hotkeys, like win + e to open a Windows explorer, win + r to

open a run command or Ctrl + c to copy some text you have highlighted, now to speed up your daily workflow, let us make

some hotkeys which opens a specific directory, a specific program as administrator and searches for some highlighted text

on Google.

Creating a Script

First off, create a new Autohotkey script, by right clicking your desktop, select New -> Autohotkey Script. Name it

shortcuts.ahk or something similar, then right click it and select Edit Script.

Leave the top lines where they are and create some blank lines after the top bit, by hitting Enter a few times.

Now to make the script more readable, we will insert a new comment containing a bunch of underscores, like so:

;____________________________________________________________________________

Comments are not executed with the rest of the code, they exist purely to make the code readable.

To attach a comment to a line of code, simply use a semicolon followed by your comment at the end of that code line, like

this:

a::b ; this code types b every time an a is typed.

Or you can comment out a whole line of code as shown above, by putting the semicolon at the beginning of said line.

To make a multiline comment, that is a comment spanning more than one line, you can use /* to start your comment

block and */ to terminate it, like so:

/*

This line is commented out (disabled).

So is this one.

*/

Page 15: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

15

DEFINING YOUR FIRST HOTKEY

To make Autohotkey listen for a keystroke and replace it with an action, we use this syntax:

Listen for this :: Take this action

For instance, insert the following in your script below your comment line:

a::b

Save your script and run it by double clicking the file.

Now open a notepad and test that every time you type the letter a, it will be replaced with a b.

End your script by right clicking your script icon in the notification area and click exit.

Open shortcuts.ahk, again by right clicking it and selecting Edit.

Delete the a::b part.

Now let us write a piece of code, that opens a specific directory on your pc. Select a location you often use, for instance I

frequently use Google Drive (on my pc it is located in the “C:\Users\AHBE\Google Drev” folder), but it could be your

Documents folder, c:\games or another folder you open up on a regular basis.

Now select the hotkey combination you want to press to open your folder, in this example I will use the ctrl + alt + g, to open my Google Drive folder. The code for doing so looks like this: ^!g::

{

run "C:\Users\ahbe\Google Drev"

Return

}

Let us analyze the code:

^!g

When Autohotkey listen for modifiers (Ctrl, Alt, Win or Shift), you will need to substitute them with either:

^ = Control

! = Alt

# = Windows Key

+ = Shift

And g is just the letter g.

Page 16: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

16

So ^!g reads as Ctrl + Alt + g.

You can find a complete modifier reference here:

https://autohotkey.com/docs/Hotkeys.htm#Symbols

And a key list here:

https://autohotkey.com/docs/KeyList.htm

Moving on to the curly brackets, this { is at the start of the code and this } at the end. When executing more than one line

of code, it is a good idea to encapsulate the code in curly brackets { }.

Curly bracket { thus mean “Begin Code Block” and curly bracket } “End Code Block”, so in this case every time you press

Ctrl+Alt+g, it will execute the code between the brackets.

Now let us look at:

run "C:\Users\ahbe\Google Drev"

If you want to execute a program, you can type run followed by the path to the program, the same way as hitting win + r

and typing a command in the run box in Windows, would run that command. For example, if you wanted to run the

calculator app you would type run “C:\Windows\System32\calc.exe” or in this case just type run calc, because the

Windows\System32 directory is included in the path variable in the Windows environmental values, so Windows already

know the path to the calculator app.

The next command Return, returns you from the subroutine you are running, in this case it is telling the script to stop

running the code located between the braces and start listening for new hotkeys again.

Copy the above into your script, so it looks like this:

;____________________________________________________________________________

^!g::

{

run "C:\Users\ahbe\Google Drev"

Return

}

;____________________________________________________________________________

Change the path "C:\Users\ahbe\Google Drev" to the folder you want to open, remember to encapsulate the path in quotation marks, at the same time you can also change ^!g to another hotkey that suits you better.

Save your script and run it, now press the shortcut key to test it works.

Page 17: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

17

DEFINING A SHORTCUTKEY TO OPEN A PROGRAM

Let us add another shortcut, to open a program by pressing a hotkey

When working on a running script, there is no need to stop it to edit the code, simply right click on the script icon in the

notification area , click Edit This Script and when you are done editing it, save it, right click the script icon and

select Reload This Script.

Now the code for opening a program, in this case the calculator, looks like this:

run “C:\Windows\System32\calc.exe”

You can type most anything after the run command, that would work when running it from the Windows run box.

That means you can also add parameters to a program, when typing the run command.

For instance, if I wanted to start PowerShell ISE as an administrator, when I hit Ctrl+Alt+p, the code would look like this:

^!p::

{

run powershell -Command "Start-Process 'powershell_ise.exe' -Verb runAs"

Return

}

;____________________________________________________________________________ Paste the above into your script and test it.

Note that you can use PowerShell to launch any program as an administrator, using this code:

run powershell Start-Process XXX -Verb RunAs

Where XXX is the path\programname of the program, for instance run powershell Start-Process cmd -Verb RunAs, will

run CMD with administrative credentials.

SPEEDING UP YOUR GOOGLE SEARCHES

Often, when searching google, you copy a piece of text by highlighting it with your mouse, pressing ctrl + c to copy it, opening your browser, opening google, clicking in the search field or address bar, pasting your text by hitting ctrl +v and hitting enter to search.

Defining a shortcut makes this process much faster:

#c::

{

Send, ^c

sleep 50

Page 18: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

18

run http://www.google.dk/search?q=%clipboard%

Return

}

;____________________________________________________________________________;

Here the shortcut win + c is bound, so all one need to do, is highlight the text to search for and activate the shortcut.

The reason for the sleep 50, between the ctrl+c action and the run command, is to give the clipboard a bit of time to register the text, you could also use ClipWait. Looking to the run command, notice you can insert URLs just like any other paths and your systems default browser will open said URL. The URL used here is: http://www.google.dk/search?q=, if you insert that into your browsers address bar and type some text after the q=, google will do a search for the defined terms.

In the run command above, the Autohotkey variable %clipboard% is used, to get the contents of the clipboard.

HOTSTRING REPLACEMENT

Hotstrings are used to auto replace text as you type it or used to launch a scripted action like you would do with a hotkey, though hotstrings are generally composed of more than one character and do not need a modifier to launch.

To define a hotstring type two colons, the text you want to use to trigger the hotstring and then two colons again.

Paste this into your script:

::wee::weekend

Reload your script, open notepad and type wee followed by a space.

Wee will now be replaced by weekend.

This can be useful while writing documentation for end users, since technicians tend to abbreviate IT and computing terms

which in turn will make reading said documentation an exercise in looking up those abbreviations on the internet.

Another useful hotstring, I myself use to autotype my company’s email, is:

;____________________________________________________________________________;

:*:@@::techcollege.dk

;____________________________________________________________________________;

This will listen for two @s in a row, the asterisk inserted between the two colons indicate that the hotstring will trigger without the need for an ending character, like space in the example above. This means that I can type any normal email address, without triggering the hotstring.

To trigger the hotstring, I would need to type test@@@ and would get this result: [email protected].

Page 19: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

19

The reason for the three @s, instead of just two, as you might expect, is that the hotstring listens for two @ standing alone and test@ is a string by itself.

For a full list of hotstring options and further examples, see https://autohotkey.com/docs/Hotstrings.htm.

COMBINING SHORTCUTS WITH DATAENTRY AND ENABLE PAUSE

Larger IT-Firms use ITIL based IT Service Management tools to delegate service requests and incidents to their IT

technicians. These systems tend to have a lot of different information boxes one need to fill out to complete a case.

Most of the settings are the same from case to case, even the log is pretty much identical in similar case types.

To make the most of your worktime and to spend time on things requiring actual thought process, you could define

shortcuts to launch the actions needed to complete different case types.

Let us say you pick a case assigned to your group, you need to assign the case to yourself and select impact, urgency and

priority from dropdown boxes and then hit the save button.

To do so, you would start AutoScriptWriter, record the necessary steps using the tabulator and the arrow keys.

Then copy the code to your script and define a shortcut to trigger the action.

Repeat for all the different scenarios you can think of, like resolving a service request, entering template text into the log

etc.

Picking a shortcut is up to personal preference, I am partial to Numpad0 – Numpad9, making it easy to remember or, if

you need a bit of help remembering the different actions assigned to the keys, making it easy to create and print a small

cheat sheet listing the actions.

There is one problem with picking the keypad to trigger actions, occasionally you might need the keypad functionality, like

when you use the calculator or enter a lot of numbers. To solve the problem, make this the first line in your script:

pause::Suspend

This will enable you to temporarily pause your script by hitting the pause button, hit the pause button again to resume.

MAKING YOUR SCRIPT RUN WHEN WINDOWS START

When you have tested your script and the shortcuts works as intended, it is time to make your script launch when Windows start, so your new shortcuts are available when you need them.

Open a file explorer and paste this into the address bar:

shell:startup

Hit enter.

This is the start directory for the user currently logged on to your machine, any files you put here will be executed at

startup. Copy your shortcuts file here.

Page 20: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

20

CONCLUSION AUTOHOTKEY

Dozens of hours can be saved creating hotkeys and hotstrings to automate and speed up daily routines. Autohotkey

furthermore has the advantage of generating editable code when it records a macro, making it easy to edit and reuse

previously generated code and distribute scripts between computers. This also make automatization of larger, more

complex jobs possible, potentially saving you hundreds of hours in the process.

ADDITIONAL SHORTCUTS AND FURTHER READING

If you need a quick refresher of AutoHotkeys basic functionality go here: http://www.howtogeek.com/56481/the-beginners-guide-to-using-an-autohotkey-script/ Some more advanced functions: https://autohotkey.com/docs/Scripts.htm

And some smart shortcuts to add to your script: http://lifehacker.com/5598693/the-best-time-saving-autohotkey-tricks-you-should-be-using

How to clean an inbox:

http://www.howtogeek.com/howto/27971/how-to-save-time-by-automating-tedious-tasks-with-autohotkey/

An index of AutoHotkey commands:

https://autohotkey.com/docs/commands/index.htm

TOOLS

Active Window Info (Window Spy):

This tool displays information about your active window, cursor coordinates etc. and is included with most Autohotkey

installations, the default installation path is C:\Program Files\AutoHotkey\AU3_Spy.exe.

Ahk2Exe:

This converts .ahk to .exe files, eliminating the need to install Autohotkey to run scripts on other machines, as with

Window Spy, this should be preinstalled in: C:\Program Files\AutoHotkey\Compiler\Ahk2Exe.exe.

Page 21: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

21

TRAINING EXERCISES

1. Create a new sheet in Excel, go to: http://listofrandomnames.com/index.cfm and generate 50 random names,

create a macro that copies the names into the sheet one by one, first names in column A, surnames in column B.

Next create a new macro that, one by one, switch the first name and surname on the list. When finished, the

macro must convert the sheet to pdf and save it as “names.pdf” on your desktop.

2. Create a hotkey that opens www.google.com, when you press Ctrl+Alt+g.

3. Create a hotkey that opens cmd and pings google.com, when you press Ctrl+Alt+p.

4. Refer to: http://lifehacker.com/5598693/the-best-time-saving-autohotkey-tricks-you-should-be-using and create

a boss key. Now Create a hotkey that turns your monitor(s) off and lock your PC in one keystroke.

5. Analyze the following code:

^!n::

IfWinExist Untitled - Notepad

WinActivate

else

Run Notepad

return

Refer to: https://autohotkey.com/docs/commands/IfExpression.htm and:

https://autohotkey.com/docs/commands/Else.htm.

What does the code do?

6. Copy this code into a new Autohotkey script:

;____________________________________________________________________________;

Gui, Add, Button, x10 y3 w150 h20 gapp, Add/Remove Programs

Gui, Add, Button, x10 y25 w150 h20 gcpt, Computermanagement

Gui, Add, Button, x10 y47 w150 h20 geve, Event Viewer / Services

Gui, Add, Button, x10 y69 w150 h20 gkey, KeyManager

Gui, Add, Button, x10 y91 w150 h20 greg, Regedit

Gui, Add, Button, x10 y113 w150 h20 gsys, System properties / Env.Vars.

Gui, Add, Button, x40 y135 w90 h20 +Center, Quit

Gui, +AlwaysOnTop

Gui, Show, x1160 y89 h157 w170, Wincmds

Return

;____________________________________________________________________________;

Page 22: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

22

app:

Sleep,200

KeyWait, Lbutton, D T3

Sleep,200

if !ErrorLevel

Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{DEL}runas /user:Domain\UserAccount "control appwiz.cpl"{Enter}

Return

cpt:

Sleep,200

KeyWait, Lbutton, D T3

Sleep,200

if !ErrorLevel

Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{DEL}runas /user:Domain\UserAccount "mmc.exe

compmgmt.msc"{Enter}

Return

eve:

Sleep,200

KeyWait, Lbutton, D T3

Sleep,200

if !ErrorLevel

Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{DEL}runas /user:Domain\UserAccount "dcomcnfg.exe"{Enter}

Return

key:

Sleep,200

KeyWait, Lbutton, D T3

Sleep,200

if !ErrorLevel

Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{DEL}control keymgr.dll{Enter}

Return

reg:

Sleep,200

KeyWait, Lbutton, D T3

Sleep,200

if !ErrorLevel

Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{DEL}runas /user:Domain\UserAccount "regedit"{Enter}

Return

sys:

Sleep,200

KeyWait, Lbutton, D T3

Sleep,200

Page 23: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

23

if !ErrorLevel

Send, {END}{SHIFTDOWN}{HOME}{SHIFTUP}{DEL}runas /user:Domain\UserAccount "control.exe

sysdm.cpl,System,3"{Enter}

Return

ButtonQuit:

GuiClose:

ExitApp

;____________________________________________________________________________;

While working with and supporting Windows 10, you might have noticed the handy shortcut menu displayed by hitting

win+x. This menu places a lot of useful commands at your fingertips. But what if you need to run those commands on a

client machine? Let us imagine you need to uninstall a program on a machine connected to a domain and the user

currently logged on does not have local administrator privileges.

Normal procedure would be to remote control the PC, connecting to the users’ session and then find the add/remove

programs command by typing it in the start menu or browsing the control panel. When found, you right click it and select

run as administrator, enter your domain\username and enter your password when

prompted.

The script above makes this process a bit easier. When launched, you are presented with

a graphical user interface with 7 buttons.

Whether you remote to a PC or are testing it on your local PC, you will need to start the

run dialog, by either hitting win+r or right click the Windows start button->Run. Then

click the Add/Remove Programs button in the GUI and then anywhere in the text field in

the run dialog.

You will now see the macro emptying the text field, if any text was present, and typing: Runas /user:Domain\UserAccount

“control appwiz.cpl” and hitting enter.

Then a command prompt window will prompt you to enter your password for Domain\UserAccount.

Close the command prompt for now. If you missed what the macro was typing, hit win+r to see the command last used.

Page 24: MACRO INTRODUCTIONbenthien.dk/Docs/Macro Opgave.pdf · USING MACROS There are a lot of free macro programs around. Some programs, like all the MS Office programs for instance, even

Benthien 2017

24

Now you need to customize the script, so that you can use it.

Open the script in notepad, hit ctrl+h and replace all instances of Domain\UserAccount with your domainname\your

username.

For instance: TCAA\TestUser like so:

Or your local PC name and username.

If you are unsure of what your PC or domain is called, or what username you are currently logged in with, simply open a

command prompt and type:

echo %userdomain% & echo %username%

And hit enter, your domain name and username will now be listed.

Save and test the script, it should prompt for your users’ password when you run it.

Deconstruct the code of the script, referring to:

https://autohotkey.com/docs/commands/Gui.htm

https://autohotkey.com/docs/commands/KeyWait.htm

https://autohotkey.com/docs/misc/ErrorLevel.htm

https://autohotkey.com/docs/Variables.htm#Operators

Google is a good resource as well.

Finally find an online webform, like:

https://www.jotform.com/form-templates/membership-application-form

With text fields such as: Name, Street Address, City, Phone number etc.

Now using what you have learned, create a new script with a GUI, that can fill out the text fields on webforms.