Search code examples
autohotkey

AHK (Auto Hot Key) Launch calculator using if/else


AHK 2.0

I am new to AHK and learning how to use IF/ELSE on pressing a hot key.

I am able to launch/activate calculator using below commands.

#HotIf WinExist("Calculator")
#c::WinActivate
#HotIf not WinExist("Calculator")
#c::Run "calc"

However I am trying to achieve the same using if/else using below commands but getting an error.

#c::
If not WinExist("Calculator")
{
    Run "calc" ; launch calculator
}
else
{
    WinActivate ; activate calculator
}

Error

Error: Hotkey or hotstring is missing its opening brace.

Line:   7
File:   C:\Users\srk\Documents\AutoHotkey\SRK_AHK.ahk

The script was not reloaded; the old version will remain in effect.

Thanks.


Solution

  • In AHK v2 you need to enclose the hotkey's body in braces, if the hotkey needs to execute more than one line. The braces serve to define a function body for the hotkey.

    In the if statements you need the braces only if the statement owns more than one line.

    #Requires AutoHotkey v2.0
    
    #c::
    {
        If not WinExist("Calculator")
            Run "calc" ; launch calculator
        else
            WinActivate ; activate calculator
    }