Search code examples
if-statementtimerautohotkey

What does this expression do? Gui % (MainGui:=!MainGui) ? "Hide" : "Show"


I find this code on this thread: Suspending, Pausing, Hiding, Pulling Up GUI Window:

Gui % (MainGui:=!MainGui) ? "Hide" : "Show"

What does it do? I guess it's a kind of a simple if expression for hotkeys, but checking the examples on the two pages I don't see where it locates.

If SetTimer is used, the counter will only increase if that code is put inside the subroutine. If put outside, the counter stops.

Gui +LastFound +AlwaysOnTop +ToolWindow -Caption
Gui, Add, Text, vcounter, 00000
Gui, Show, NoActivate 

SetTimer, Update, 100 ; 100 ms
Update:
    counter++
    GuiControl,, counter, %counter%
    ^esc::Gui % (MainGui:=!MainGui) ? "Hide" : "Show"
Return 

Solution

  • It is a kind of operator in expressions:

    Ternary operator [v1.0.46+]. This operator is a shorthand replacement for the if-else statement. It evaluates the condition on its left side to determine which of its two branches should become its final result. For example, var := x>y ? 2 : 3 stores 2 in Var if x is greater than y; otherwise it stores 3. To enhance performance, only the winning branch is evaluated (see short-circuit evaluation).

    The command ^esc::Gui % (MainGui:=!MainGui) ? "Hide" : "Show" has two parts.

    1. (MainGui:=!MainGui) Switches the value of the variable MainGui to it's oposite, usually from True to False and vice versa.
    2. Uses the standard form of the ternary operator to check the value of the variable MainGui. If it is True it uses the value Hide, if it is False it uses the value Show.

    ^esc::Gui % (MainGui:=!MainGui) ? "Hide" : "Show" translates to one of the following after all evaluations:
    1. If MainGui is True ==> Gui Hide
    2. If MainGui is False ==> Gui Show

    Short explanation: The ^esc hotkey hides the Gui if it is active, shows it if it is hidden.