Jump to content

GUIGetMsg for an array of buttons


jftuga
 Share

Recommended Posts

local $g_btn[11]

for $i = 1 to 10
$g_btn[$i] = GUICtrlCreateButton("show", $x+300, $y-6, 100 )
next

$msg = GUIGetMsg()
select
case $msg = $GUI_EVENT_CLOSE
     exitloop
case $msg = ????
     do something with button $i
endselect

How to I create a $msg comparison for the 10 different buttons? I would prefer not having to write 10 different versions of:

case $msg = $g_btn[1] ; (and then 2,3,4...)

Thanks,

-John

Link to comment
Share on other sites

Because you're creating the buttons one right after the other, you could do it this way.

Switch $msg
    Case $GUI_EVENT_CLOSE
        ExitLoop
    Case $g_btn[1] To $g_btn[10] ; this will detect any of the buttons
        For $I = 1 To 10
            If $msg = $g_btn[$I] Then
;~          do something with button $i
            EndIf
        Next
EndSwitch

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

There is no need to loop thru the button-id's.

#include <GUIConstantsEx.au3>

Global $aBtnIds[9]
$hGui=GUICreate('Buttontest', 110, 110)
For $i = 0 To 8
    $aBtnIds[$i] = GUICtrlCreateButton($i + 1, 10 + Mod($i,3) * 30, 10 + Int($i/3) * 30, 25, 25)
Next
GUISetState()

While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $GUI_EVENT_CLOSE
            Exit
        Case $aBtnIds[0] To $aBtnIds[8]
            MsgBox(0, 'Button', 'No. ' & $msg - $aBtnIds[0] + 1 & ' was clicked',0,$hGui)
    EndSwitch
WEnd

Link to comment
Share on other sites

@AutoBert: thanks, this is a great solution that you have provided!

One more question: what does the optional 4th arg to MsgBox do, $hGui? The help file does not make this clear.

edit:

I am getting this error message:

case $g_btn[0] to $g_btn[10]

case $g_btn[0] ^ ERROR

Error: Illegal text at the end of statement (one statement per line).

any ideas?

edit2:

I was using select ... endselect and you are using switch ... endswitch. What is the difference between these?

-John

Edited by jftuga
Link to comment
Share on other sites

The 4th arg is the parentwindow of the messagebox. When it is used:

  • you see only 1 task of your skript in then taskbar
  • the messagebox is allways before the parentwindow
The syntax for select is
While 1
$msg = GUIGetMsg()
Select
Case $msg=$GUI_EVENT_CLOSE
Exit
Case $msg>=$aBtnIds[0] And $msg<=$aBtnIds[8]
MsgBox(0, 'Button', 'No. ' & $msg - $aBtnIds[0] + 1 & ' was clicked',0,$hGui)
EndSelect
WEnd
Edited by AutoBert
Link to comment
Share on other sites

@AutoBert: thanks, this is a great solution that you have provided!

One more question: what does the optional 4th arg to MsgBox do, $hGui? The help file does not make this clear.

It means that the message box is a child window to the main GUI, and in this case it means that as long as the msgbox is up, you can't interact with the window that created it.

edit:

I am getting this error message:

case $g_btn[0] to $g_btn[10]

case $g_btn[0] ^ ERROR

Error: Illegal text at the end of statement (one statement per line).

any ideas?

See below.

edit2:

I was using select ... endselect and you are using switch ... endswitch. What is the difference between these?

-John

With a select comparison, you're only able to check one value at a time, with Switch, you can compare 1, many, or a range of values on the same line. This shortens your code considerably.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

These never really is a need to use a select statement, always go for switch.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

  • Moderators

guinness,

These never really is a need to use a select statement, always go for switch

I am not sure I entirely agree with you there. Although I certainly prefer to use Switch, I think that there is a place for Select at times. Let me offer a couple of examples for discussion. :)

This first one is, I accept, a matter of personal taste. Although the 2 are functionally identical, personally I find the Select structure easier to understand:

$vVar_1 = False
$vVar_2 = True

Select
    Case $vVar_1 And $vVar_2
        ConsoleWrite("Select 1" & @CRLF)
    Case (Not $vVar_1) And $vVar_2
        ConsoleWrite("Select 2" & @CRLF)
    Case $vVar_1 And (Not $vVar_2)
        ConsoleWrite("Select 3" & @CRLF)
    Case (Not $vVar_1) And (Not $vVar_2)
        ConsoleWrite("Select 4" & @CRLF)
EndSelect

Switch $vVar_1
    Case False
        Switch $vVar_2
            Case False
                ConsoleWrite("Switch 4" & @CRLF)
            Case True
                ConsoleWrite("Switch 2" & @CRLF)
        EndSwitch
    Case True
        Switch $vVar_2
            Case False
                ConsoleWrite("Switch 3" & @CRLF)
            Case True
                ConsoleWrite("Switch 1" & @CRLF)
        EndSwitch
EndSwitch

But I cannot see how this second example can be replaced by a simple Switch if we assume that $vVar_3 has no constraints on its value and so the To keyword cannot be used within the Case definition:

$iMin = 3
$iMax = 7
$vVar_3 = 9999

Select
    Case $vVar_3 < $iMin
        ConsoleWrite("Below min" & @CRLF)
    Case $vVar_3 > $iMax
        ConsoleWrite("Above max" & @CRLF)
    Case Else
        ConsoleWrite("In range" & @CRLF)
EndSelect

But it is early on a Saturday morning and I am always willing to learn - so any offers from the floor? :D

M23

Edited by Melba23
Typo

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Melba23

$iMin = 3
$iMax = 7
$vVar_3 = 9999

Switch True
    Case $vVar_3 < $iMin
        ConsoleWrite("Below min" & @CRLF)
    Case $vVar_3 > $iMax
        ConsoleWrite("Above max" & @CRLF)
    Case Else
        ConsoleWrite("In range" & @CRLF)
EndSwitch

$vVar_1 = False
$vVar_2 = True

Switch True
    Case $vVar_1 And $vVar_2
        ConsoleWrite("Select 1" & @CRLF)
    Case (Not $vVar_1) And $vVar_2
        ConsoleWrite("Select 2" & @CRLF)
    Case $vVar_1 And (Not $vVar_2)
        ConsoleWrite("Select 3" & @CRLF)
    Case (Not $vVar_1) And (Not $vVar_2)
        ConsoleWrite("Select 4" & @CRLF)
EndSwitch

Link to comment
Share on other sites

  • Moderators

AZJIO,

Very clever. :thumbsup:

M23

Edited by Melba23
At least spell the name right!

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

AZJIO got there before I did. It was a comment Valik made ages ago and it has stuck with me ever since.

UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Link to comment
Share on other sites

AZJIO

You seem to be are very good at lateral thinking as I have noticed you have come up with a number of solution like this to problems others have said were very difficult or impossible. Your answers have given me inspiration to solve some of my own problems. In this case however I would say that Melba23 Select version or a an IF IF ELSE would be a lot simpler would be easier to understand in 6 months time.

"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the universe trying to build bigger and better idiots. So far, the universe is winning."- Rick Cook

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...