July 3, 2020

AutoHotkey: Customize Button Message Box

It is not so easy in AutoHotkey to use a custom Message Box with customized Text on the Buttons or as many buttons as wished.
I present here 2 approaches and share some code.

 

Tweaking MsgBox

Using a Timer

As explained in the MsgBox Help page (https://www.autohotkey.com/docs/commands/MsgBox.htm)
the name of the buttons can be changed by following this example based on a timer:

Using OnMessage

(I don't remember where I have found this.)

OnMessage(0x44, "OnTocStyleMsgBox")
MsgBox 0x23, Toc Style, Select your Table of Content style:
OnMessage(0x44, "")
sTocStyle = bullet-white ; Default
IfMsgBox, No
  sTocStyle = none-yellow
IfMsgBox, Cancel
  sTocStyle = num-white

Add the function:
OnTocStyleMsgBox() {
DetectHiddenWindows, On
Process, Exist
If (WinExist("ahk_class #32770 ahk_pid " . ErrorLevel)) {
    ControlSetText Button1, bullet-white
    ControlSetText Button2, none-yellow
    ControlSetText Button3, num-white
}
}

Using Gui Button

In this forum enty (https://www.autohotkey.com/boards/viewtopic.php?f=6&t=35382) you can find some nice code for Custom Boxes.

The interesting one here is the BtnBox function.

I have modified it to add a Default parameter for preselecting a button.

See code below also available in GitHub ahk/lib

ButtonBox(Title := "", Prompt := "", List := "", Seconds := "",Def:=1) {
;-------------------------------------------------------------------------------
    ; show a custom MsgBox with arbitrarily named buttons
    ; return the text of the button pressed. 
    ; If Timeout returns "Timeout". If Cancelled or Closed, returns "ButtonBox_Cancel"
    ;---------------------------------------------------------------------------
    ; Title is the title for the GUI
    ; Prompt is the text to display
    ; List is a pipe delimited list of captions for the buttons
    ; Seconds is the time in seconds to wait before timing out. Leave blank to wait indefinitely

    ; create GUI
    Gui, ButtonBox: New,, %Title%
    Gui, -MinimizeBox
    Gui, Margin, 30, 18
    Gui, Add, Text,, %Prompt%
    Loop, Parse, List, | 
    {  
        If (A_Index = Def)
            Gui, Add, Button, % (A_Index = 1 ? "" : "x+10") " gBtn Default" , %A_LoopField%
        Else
            Gui, Add, Button, % (A_Index = 1 ? "" : "x+10") " gBtn", %A_LoopField%
    }
    Gui, Show

    ; main wait loop
    Gui, +LastFound
    WinWaitClose,,, %Seconds%

    if (ErrorLevel = 1) {
        Result := "TimeOut"
        Gui, Destroy
    }

return Result


    ;-----------------------------------
    ; event handlers
    ;-----------------------------------
    Btn: ; all the buttons come here
        Result := A_GuiControl
        Gui, Destroy
    return

    ButtonBoxGuiClose:  ; {Alt+F4} pressed, [X] clicked
    ButtonBoxGuiEscape: ; {Esc} pressed
        Result := "ButtonBox_Cancel"
        Gui, Destroy
    return
}

 

No comments:

Post a Comment