An improved GUICtrlSetOnEvent

1 post in this topic

#1 ·  Posted (edited)

Inspired from

I created a UDF that I have been using to replace GUICtrlSetOnEvent, not using Opt("GUIOnEventMode").

AutoIt's GUICtrlSetOnEvent function only supports mouse clicks without parameters at this moment, this UDF works on the same premise but gives the user some more flexibility, in just 61 lines of code.

Here is an example of what A callback will look like

Func MyCallBackFunction(Const $wParam, ByRef $iCtrlId, ByRef $uData, ByRef $hWnd)

    Switch $wParam
        Case $WM_HOVERIN
            ConsoleWrite("Entering control; attached data = " & $uData & @CRLF)
        Case $WM_HOVEROUT
            ConsoleWrite("Leaving control" & @CRLF)
        Case $WM_LBUTTONDOWN
            ConsoleWrite("Left mousebutton DOWN" & @CRLF)
        Case $WM_LBUTTONUP
            ConsoleWrite("Left mousebutton UP" & @CRLF)
        Case $WM_MBUTTONDOWN
            ConsoleWrite("Middle mousebutton DOWN" & @CRLF)
        Case $WM_MBUTTONUP
            ConsoleWrite("Middle mousebutton UP" & @CRLF)
        Case $WM_RBUTTONDOWN
            ConsoleWrite("Right mousebutton DOWN" & @CRLF)
        Case $WM_RBUTTONUP
            ConsoleWrite("Right mousebutton UP" & @CRLF)



More examples can be found in the zip file.

Good 2 know

  1. GuiDelete($hWnd) used together with $WM_LBUTTONUP will cause the AutoIt script to crash
  2. $WM_HOVERIN and $WM_HOVEROUT ARE NOT real Windows Message codes and will only work with with this UDF
  3. Your callback functions MUST have 4 parameters assigned to it.

That's about it.

Feel free to pitch some improvements.




Edited by tarretarretarre
1 person likes this


TeenyScript 2016-09-05 - A new  way of programming in AutoIt

UDFs created\updated 2016
_IEEmbedded2 UDF - A _IECreateEmbedded() decedent
miniSQL - A simple Standalone PDO-syntax-like MySQL-library with AutoitObject
Advanced DllCall and DllStruct AutoIt Code Generator - Automatically generates code for DllCall and more.


Share this post

Link to post
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

  • Similar Content

    • shotiko
      GUIState 7 OnEvent
      By shotiko
      here I am writing simple gui with text processing capabilities.
      i have main gui, background picture, all buttons with labels over them 2 static buttons (1 present here)
      Opt("GUIOnEventMode", 1) and includes
      $main = GUICreate("Title", 961, 721); Main Window $bgpic = GUICtrlCreatePic(@WorkingDir & "\960x720.jpg", 0, 0, 960, 720); use background picture $quitBtn = GUICtrlCreateButton("Quit", 885, 685, 95, 40) GUICtrlSetOnEvent($quitBtn, "_exit"); assign quit button to function "exit" _GuiCtrlMakeTrans(-1, 1) $quitLabel = GUICtrlCreateLabel("Quit", 885, 685, 95, 40, BitOR($SS_CENTER, $BS_BOTTOM)) GUICtrlSetFont(-1, 14, 400, 0, "Tahoma") GUICtrlSetBkColor(-1, $GUI_BKCOLOR_TRANSPARENT) GUICtrlSetColor(-1, 0x962129) GUISetState(@SW_SHOW)
      then i have the code for creating buttons dynamically from information in file
      Dim $Button[$NumberFromText] $startX = 48 $startY = 24 $fromLeft = 240 $bHeigh = 160 $bWidth = 50 Dim $1to4btn[0] For $x = 0 To _Min(UBound($Button) - 1, 3) ; creates maximum 4 button, label $Button = GUICtrlCreateButton($x, $startX, $startY, $bHeigh, $bWidth); create buttons _GuiCtrlMakeTrans(-1, 1) ; transparency 255 Solid, 0 Transparent $serverLabel = GUICtrlCreateLabel(FileReadLine($configF, $SN), _ ; read 1st line and 5 below on each iteration $startX, $startY, $bHeigh, $bWidth, BitOR($SS_CENTER, $SS_CENTERIMAGE, $WS_EX_TRANSPARENT)); GUICtrlSetFont(-1, 14, 400, 0, "Tahoma"); set font and size GUICtrlSetColor($serverLabel, 0x04A111); set color of font GUICtrlSetBkColor($serverLabel, $GUI_BKCOLOR_TRANSPARENT); make label Background transparent $SN += 5; read 5 lines below $startX = $startX + $fromLeft $btnArray=_ArrayAdd($1to4btn, GUICtrlGetHandle($Button)) Next since buttons are created under the label $Button and I couldn't conacenate $Button[$i] , I created array and place handles into it and connected static buttons with
      GUICtrlSetOnEvent($cancelBtn,"cancelFunc") and it worked
      now i tried using handles to assign functions to buttons but it fails with GUICtrlSetOnEvent()
      also tried GUISetOnEvent($GUI_EVENT_PRIMARYDOWN, "funcForFirstButton", $1to4btn[0])
      if I assign without handle it works by clicking anywhere on MainGUI
      While loop includes only sleep(10)
      Window starts as inactive and return code 7
      If i click dynamically created buttons, window loses focus . clicking anywhere else focuses window
      this is _GuiCtrlMakeTrans function (found here on forums some time ago)
      also created simple button on the same mainGUI and tried but didn't work
      $try=GUICtrlCreateButton("TRY",250,150,100,35) GUICtrlSetOnEvent(-1,"FunctionOne") ; shows messagebox and write console  
    • byarotsky
      Issue with displaying GUICtrlCreateRadio in a GUICtrlSetOnEvent script
      By byarotsky
      I am working on a script that pulls the current time from the internet and then reads contents from our backup server based on the month and week folders that are already created. This script will ultimate pass variables to another program that will restore the data from the respective folder to the computer that the script it running on. The script is built to find the 'windows' folders in the server structure which is \\server\serverfolder\01_16\3week
      \\server\serverfolder - is the server share
      01_16 - is month and year as to sort properly
      3week - is obviously the week
      Within the week folder there are user folders (eg. bsmith, jdoe, ganderson), in these folders are backups of full hard drives with include the windows folder which we are looking for.The script is running and is fully function the first time that it is run. I have also added a back button so if for some reason you are in the wrong list of folders you can navigate to the correct folder and then show the results again.
      The issue I am having is that I can show the contents and everything works well, unless I use the back button and navigate to a different set of folders (different week). The radio buttons do not respond properly. They will show both incorrect data and the count of radio buttons is not being updated.
      I have attempted to look for a solution and have tried many different ideas, but I just don't fully understand how a GUICtrlCreateRadio in a for loop with GUICtrlSetOnEvent should work.
      Any suggestions would be greatly appreciated. I apologize for the messy code.
      #include <Array.au3> #include <File.au3> #include <GUIConstantsEx.au3> ; #FUNCTION# ==================================================================================================================== ; Name ..........: _GetTimeOnline ; Description ...: Retrieve the current date and time from TimeAPI.org. ; Syntax ........: _GetTimeOnline($iTimeZone) ; Parameters ....: $iTimeZone - An integer value of the timezone . ; 0 - UTC (Universal Time) ; 1 - EST (Eastern Time) ; 2 - CST (Central Time) ; 3 - MST (Mountain Time) ; 4 - PST (Pacific Time) ; 5 - AKST (Alaska Time) ; 6 - HAST (Hawaii-Aleutian Time) ; Return values .: Success: Returns the current Date and Time in the format YYYY/MM/DD HH:MM:SS ; Failure: Sets @error to non-zero and returns the same format as a successful return but using the system time. ; Author ........: guinness ; Link ..........: According to http://www.programmableweb.com/api/timeapi, this is for non-commercial use. ; Example .......: Yes ; =============================================================================================================================== Opt("GUIResizeMode", 1) Opt("GUIOnEventMode", 1) Global $vGUI_V = 450 Global $vGUI_ = 400 Local $ServerPath = "\\vault\backups\" Local $aFileList, $Current_Radio, $CurrentMonthFolder Local $Current_Gui = GUICreate("Test", 450, 400) Local $GuiBack = GUICtrlCreateButton("Back", 200, 250, 40, 40) GUICtrlCreateLabel("Please select the Windows folder to use", 20, 20) GUICtrlSetOnEvent($GuiBack, "BackPressed") GUISetOnEvent($GUI_EVENT_CLOSE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_MINIMIZE, "SpecialEvents") GUISetOnEvent($GUI_EVENT_RESTORE, "SpecialEvents") _GetTimeOnline(2) ;Central time zone _SelectFolder() While 1 Sleep(100) WEnd Exit Func _GetTimeOnline($iTimeZone) ; Retrieve the current time from TimeAPI.org. Ideal if your Windows clock is out of sync. Local $aTimeZone[7] = ['utc', 'est', 'cst', 'mst', 'pst', 'akst', 'hast'] Local $sRead = BinaryToString(InetRead('http://www.timeapi.org/' & $aTimeZone[$iTimeZone] & '/now?format=\Y/\m/\d%20/\H:\M:\S')) If @error Then SetError(1, 0, @YEAR & '/' & @MON & '/' & @MDAY & '/' & @HOUR & ':' & @MIN & ':' & @SEC) EndIf Local $aDays = StringSplit($sRead, "/") ; Split the string of days using the delimiter "," and the default flag value. ; For $i = 1 To $aDays[0] ; Loop through the array returned by StringSplit to display the individual values. ; MsgBox(4096, "", "$aDays[" & $i & "] - " & $aDays[$i]) ; Next $CurrentMonthFolder = $ServerPath & $aDays[2] & "_" & StringTrimLeft($aDays[1], 2) & "\" & Ceiling((@MDAY + (7 - @WDAY)) / 7) & "week" EndFunc ;==>_GetTimeOnline Func _SelectFolder() Local Const $sMessage = "Select users folder to restore data from:" ; Display an open dialog to select a file. Local $sFileSelectFolder = FileSelectFolder($sMessage, $CurrentMonthFolder) If @error Then ; Display the error message. ; MsgBox($MB_SYSTEMMODAL, "", "No folder was selected.") Exit Else ; Display the selected folder. ; MsgBox($MB_SYSTEMMODAL, "", "You chose the following folder:" & @CRLF & $sFileSelectFolder) $aFileList = _FileListToArrayRec($sFileSelectFolder, "Windows", 14, -3, $FLTAR_SORT) If @error = 1 Then MsgBox($MB_SYSTEMMODAL, "", "Path was invalid or Windows folder not found.") _SelectFolder() EndIf If @error = 9 Then MsgBox($MB_SYSTEMMODAL, "", "No file(s) were found.") _SelectFolder() EndIf EndIf $CurrentMonthFolder = $sFileSelectFolder _ShowGui() EndFunc ;==>_SelectFolder Func _ShowGui() Local $startline = 20 If @error Then MsgBox(4096, "ERROR", "Error occured, no INI or incorrect Sections") Else For $i = 1 To $aFileList[0] $Current_Radiou = GUICtrlCreateRadio($aFileList[$i], 25, $startline + 20 * $i, 400) GUICtrlSetOnEvent(-1, "myEvent") ; This will tell us which radio was clicked Next EndIf GUISetState(@SW_SHOW, $Current_Gui) EndFunc ;==>_ShowGui Func BackPressed() ; MsgBox($MB_SYSTEMMODAL, "Go Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle & " CtrlHandle=" & @GUI_CtrlHandle) GUISetState(@SW_HIDE, $Current_Gui) _SelectFolder() EndFunc ;==>BackPressed Func myEvent() For $x = 1 To $aFileList[0] + 6 ; this is broken If GUICtrlRead($x) = 1 Then MsgBox(0, GUICtrlRead($x), GUICtrlRead($x, 1)) ;this is the path to the profile Next EndFunc ;==>myEvent Func SpecialEvents() Select Case @GUI_CtrlId = $GUI_EVENT_CLOSE ; MsgBox($MB_SYSTEMMODAL, "Close Pressed", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) Exit Case @GUI_CtrlId = $GUI_EVENT_MINIMIZE ; MsgBox($MB_SYSTEMMODAL, "Window Minimized", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) Case @GUI_CtrlId = $GUI_EVENT_RESTORE ; MsgBox($MB_SYSTEMMODAL, "Window Restored", "ID=" & @GUI_CtrlId & " WinHandle=" & @GUI_WinHandle) EndSelect EndFunc ;==>SpecialEvents  
    • 232showtime
      Problem with GUICtrlSetOnEvent
      By 232showtime
      need little help from the expert, I don't know whats wrong with my script, only one button is working, button6.
      #include <ButtonConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <Misc.au3> SelectFolder() While 1 Sleep(10) WEnd Func SelectFolder() Opt("GUIOnEventMode", 1) If _Singleton("Uploader", 1) = 0 Then GUISetState(@SW_SHOW) Else GUICreate("Uploader", 208, 139, 211, 128, -1, $WS_EX_TOPMOST) GUISetOnEvent($GUI_EVENT_CLOSE, "CloseW") GUICtrlCreateButton("Load", 16, 16, 75, 25) GUICtrlCreateButton("TQEngFolder", 112, 16, 75, 25) GUICtrlCreateButton("Scanned", 16, 56, 75, 25) GUICtrlCreateButton("Incoming", 112, 56, 75, 25) GUICtrlCreateButton("Outgoing", 16, 96, 75, 25) GUICtrlCreateButton("Button6", 112, 96, 75, 25) GUICtrlSetOnEvent(-1, "Load") GUICtrlSetOnEvent(-1, "TQEngFolder") GUICtrlSetOnEvent(-1, "Scanned") GUICtrlSetOnEvent(-1, "Incoming") GUICtrlSetOnEvent(-1, "Outgoing") GUICtrlSetOnEvent(-1, "Button6") GUISetState(@SW_SHOW) EndIf EndFunc ;==>SelectFolder Func CloseW() Select Case @GUI_CtrlId = $GUI_EVENT_CLOSE GUISetState(@SW_HIDE, "PDB") EndSelect EndFunc ;==>CloseW Func Load() MsgBox(64, "Load", "You clickedLoad") EndFunc ;==>Load Func TQEngFolder() MsgBox(64, "TQEngFolder", "You clicked TQFolder") EndFunc ;==>TQEngFolder Func Scanned() MsgBox(64, "Scanned", "You clicked Scanned") EndFunc ;==>Scanned Func Incoming() MsgBox(64, "Incoming", "You clicked Incoming") EndFunc ;==>Incoming Func Outgoing() MsgBox(64, "Outgoing", "You clicked Outgoing") EndFunc ;==>Outgoing Func Button6() MsgBox(64, "Availble", "You clicked button 6") EndFunc ;==>Button6  
    • zaetep
      How can a guictrlsetonevent function stop working sometimes??
      By zaetep
      Hi, I'm totally stumped by this one. I have a general purpose input function that allows a user to select one of a group of radio buttons. As soon as a radio is clicked the gui deletes and returns the text of the choice to the calling function.
      It works really nicely but i have two functions that call it and the event function for selecting a button never runs, it just gets stuck in the loop waiting for a response.
      It still works in all other cases (in the same execution of the program). And cutting and pasting (to check for typos etc) the call and the function to a test file (not connected to the rest of the code) it works.
      Is there anything that can stop an event function being called?
      the function is:
      ~ ;takes possible choices separated by | in a string, returns the chosen answer or "input cancelled" if closed
      Func RadioQBox($title, $prompt, $choices)
      Local $c = StringSplit($choices, "|");make array into string

      Local $rads[$c[0] + 1] = [$c[0]];array for control ids
      Local $ypos = 50, $msg, $sel;set y postion
      Local $hgt = ($c[0] * 40) + 100;set height

      GUISetState(@SW_DISABLE, $siteGui);disable main gui
      Local $radGui = GUICreate($title, 500, $hgt, -1, -1, BitOR($WS_CAPTION, $WS_POPUP, $WS_SYSMENU), $WS_EX_TOPMOST);build form
      GUICtrlCreateGroup($prompt, 50, 10, 400, $hgt - 10)

      For $i = 1 To $c[0];create radios
      $rads[$i] = GUICtrlCreateRadio($c[$i], 60, $ypos, 380, 15)
      GUICtrlSetOnEvent($rads[$i], "RadioChoice");set on event function
      $ypos = $ypos + 40


      Global $RadChoice = 0;selected flag

      While Not $RadChoice

      ;db("Radiochoice answer")
      For $i = 1 To $c[0]
      If $RadChoice = $rads[$i] Then
      $sel = $c[$i]
      $RadChoice = 0
      If $sel = 'other' Then
      db("Radiochoice other")
      $sel = InputBox($title, $prompt & @CRLF & "It is recommended that you make your answer roughly the same length and format as the other options")

      GUISetState(@SW_ENABLE, $siteGui)
      Return $sel
      EndFunc ;==>RadioQBox

      The event is

      Func RadioChoice()
      $RadChoice = @GUI_CtrlId
      ;db("radiochoice event", @GUI_CtrlId, @GUI_WinHandle, @GUI_CtrlHandle)
      EndFunc ;==>RadioChoice

      Hope you can help