Create keyboard shortcuts for coding in C# using AutoHotKey

AutoHotKey is a remarkably useful piece of free software which allows you to automate any repetitive keyboard or typing task. It effectively allows you to program any key, or any combination of keys, to any command of your choosing.

Here, I will show how to use AutoHotKey to make writing C# code a little faster and easier.

I often use the Spotify web app to listen to music. One big disadvantage of this is that I can’t use the pause/play button on my keyboard to control it. And the app has a really fiddly tiny little pause/play button that is difficult to hit with the mouse on my 24″ screen…

The F8 key on my keyboard has a pause/play icon, so I decided to reprogram this key. In AutoHotKey, I created the following script:

F8::
 Send #3
 Sleep (20)
 Send {space}
 Send #3
 Return

…or, in English:

If F8 is pressed…
Simulate pressing Windows + 3 (this opens the Spotify window – its icon is the third icon on my taskbar)

Wait for 20ms (to make sure the window’s had time to open)
Simulate pressing the space key (this pauses the music if the Spotify window is in focus)
Simulate pressing Windows + 3 again (to re-hide Spotify)
Finished!

This is only a basic script, so it doesn’t behave properly if Spotify is already the active window, or if Spotify isn’t already open in the background, but these aside, it works quite well. Hitting F8 now pauses and plays quite happily,

As a wannabe C# programmer, I’ve come to realise that there is a lot of repetitive typing involved. I’ve put together a few examples that I’ve written, and if I seem to use them quite often I may well write some more.

Create curly brackets

::{}::
Send {{}
Send {Enter}{Enter}
Send {}}
Send {Up}
Return

What this does: typing {} creates a pair of curly brackets with a blank line between them. The caret should finish in this blank line.

Create a for loop

::fori::
Send for (int i {=} 0{;} i < {;} i{+}{+}){Enter}
Send {Up}{Right 20}
Return

What this does: typing fori should add the following line: for (int i = 0; i < ; i++). The caret finishes before the second semi-colon so you can enter the upper value for i.

Create a try-catch

::trycatch::
Send try{Enter}
Send {{}{Enter 2}
Send {}}{Enter}
Send catch{Enter}
Send {{}{Enter 2}
Send {}}
Send {Left}{Up 5}
Return

What this does: typing trycatch will create two pairs of brackets, each with try and catch. The caret will be within the try section.

Leave a Reply

Your email address will not be published.

Time limit is exhausted. Please reload CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: