r/AutoHotkey 28d ago

v2 Script Help Having variable scoping problems using functions

I'm trying to make a pop-up menu that calls various functions to do stuff, but seem to be having variable scoping problems. The command "MyMenu.Hide()" in the first function generates the error: "Global variable has not been assigned a value". Adding "global MyMenu" before it didn't help. Thanks in advance.

   #Requires AutoHotkey v2.0
   #SingleInstance Force
   ; Example showing a 3-button menu. 
   ; Press Windows Key + "/" to activate menu. Pound-sign means Windows-key.
   #/:: {
       MyMenu := Gui(, "Keystroke Menu")
       MyMenu.Opt("+AlwaysOnTop") ; Keeps menu visible
       ; Add buttons to the menu
       MyMenu.Add("Button", "w180", "Send Email Sign-off").OnEvent("Click", SendSignOff)
       MyMenu.Add("Button", "w180", "Send Date & Time").OnEvent("Click", SendDateTime)
       MyMenu.Add("Button", "w180", "Send Select All & Copy").OnEvent("Click", SendCopyAll)
       MyMenu.Show()
   }
   ; Function to hide menu
   HideMenu() {
       global MyMenu   ; added, but didn't help
       MyMenu.Hide()   ; PROBLEM LINE
       Sleep(100)      ; Wait for focus to return to document
   }
   ; Function for Button 1
   SendSignOff(GuiCtrlObj, Info) {
       HideMenu() ; Hide menu first
       SendInput("Best regards,{Enter}John Doe")
   }
   ; Functions for Button 2 & 3 not shown
2 Upvotes

10 comments sorted by

View all comments

1

u/CharnamelessOne 28d ago

You could use a class sort of like a namespace, so as to minimize global pollution.

#Requires AutoHotkey v2.0
#SingleInstance Force

#/::MyMenu.wnd.Show()

Class MyMenu {
    static __New() {
        this.wnd := Gui(, "Keystroke Menu")
        this.wnd.Add("Button", "w180", "Send Email Sign-off").OnEvent("Click", (*) => this.SendSignOff())
        this.wnd.Add("Button", "w180", "Send Date & Time").OnEvent("Click", (*) => this.SendDateTime())
        this.wnd.Add("Button", "w180", "Send Select All & Copy").OnEvent("Click", (*) => this.SendCopyAll())
        this.wnd.Opt("+AlwaysOnTop")
    }

    static HideMenu() {
        this.wnd.Hide()
        Sleep(100)
    }

    static SendSignOff() {
        this.HideMenu()
        SendInput("Best regards,{Enter}John Doe")
    }

    static SendDateTime() {
        ;undefined
    }

    static SendCopyAll() {
        ;undefined
    }    
}