AHK v2: Encapsulation of Selection List GUI

313 views Asked by At

I've been working on converting an AutoHotkey script from v1 to v2, and I've encountered a challenge with encapsulating a Selection List GUI. I've spent hours searching for a solution online, but I haven't been able to find one. The AHK v2 help file, while comprehensive, is not very beginner-friendly, and I'm struggling to find the correct syntax.

The specific issue I'm facing involves encapsulating the GUI creation code within a function, and I want to avoid using global variables. I want to call this function, select an item from a list, and have that item returned to the caller.

I believe I'm not the only one struggling to transition from AHK v1 to AHK v2. I'm also surprised that there is no tag for AutoHotkey v2.

1

There are 1 answers

3
q-l-p On
#Requires AutoHotkey v2.0
#SingleInstance Force


; Driver Code
ItemList := ["Item 1", "Item 2", "Item 3", "Item 4", "Item 5"]
Loop
{
    item := "You selected " OpenListSelectionGui(ItemList, "Select an Item")
    info := "Do you want to continue the tests?"
    test := MsgBox(item "`n`n" info, "AutoHotkey v2 GUI Testing", "OKCancel")
    if (test == "Cancel")
        ExitApp
}

; GUI Encapsulation
OpenListSelectionGui(pList, pGuiTitle)
{
    SelectedValue := ""
    ListGui := Gui("ToolWindow", pGuiTitle)
    ListGui.OnEvent("Close", Gui_Close)
    ListCtrl := ListGui.AddListBox("Choose1 r5", pList)
    ListGui.AddButton("Default", "Select").OnEvent("Click", Gui_Close)
    ListGui.Show()
    
    While (!SelectedValue)
    {
        Sleep 222
    }

    Return SelectedValue

    Gui_Close(*)
    {
        SelectedValue := ListCtrl.Text
        ListGui.Destroy
    }
}