A caution about combining Gui.Add and onEvent functions
Posted: 19 Apr 2023, 11:39
Combining Gui.Add() and onEvent() functions on a single line is appealing as a programming technique (see below). However, this can lead to unexpected issues.
Gui.Add() returns the GuiControl object (GuiCtrl) for the control that was added. This is a powerful reference that you will want to have if you are going to interact with the control.
OnEvent() when registered to a GuiCtrl without a Callback returns a null string
When you combine the Gui.Add() and the onEvent() functions in a single line of code (see below) the final value returned is the NullString returned by onEvent() not the GuiCtrl returned by GuiAdd(). When combined the GuiCtrl object returned by Gui.Add() is used to register the onEvent() with the newly added control and the return value is a string returned by onEvent().
THIS LINE IS VALID CODE:
RA := main.addRadio("vTesting", "Test1").onEvent("Click", React) ;here RA = NullString (no onEvent callback)
...
ControlClick RA ;Generates an error because RA is not a valid GuiCtrl object
IT IS NOT THE SAME AS THE FOLLOWING (WHICH IS ALSO VALID CODE):
RA := main.addRadio("vTesting", "Test1") ;here RA = the GuiCtrl object for the added radio button
RA.onEvent("Click", React)
...
ControlClick RA ;Clicks the RA radio button
--- THIS PRECAUTION HOLDS FOR COMBINING FUNCTIONS ANYWHERE IN AHK ---
Moderator's Note: Moved from Scripts and Functions to Tips and Tricks
Gui.Add() returns the GuiControl object (GuiCtrl) for the control that was added. This is a powerful reference that you will want to have if you are going to interact with the control.
OnEvent() when registered to a GuiCtrl without a Callback returns a null string
When you combine the Gui.Add() and the onEvent() functions in a single line of code (see below) the final value returned is the NullString returned by onEvent() not the GuiCtrl returned by GuiAdd(). When combined the GuiCtrl object returned by Gui.Add() is used to register the onEvent() with the newly added control and the return value is a string returned by onEvent().
THIS LINE IS VALID CODE:
RA := main.addRadio("vTesting", "Test1").onEvent("Click", React) ;here RA = NullString (no onEvent callback)
...
ControlClick RA ;Generates an error because RA is not a valid GuiCtrl object
IT IS NOT THE SAME AS THE FOLLOWING (WHICH IS ALSO VALID CODE):
RA := main.addRadio("vTesting", "Test1") ;here RA = the GuiCtrl object for the added radio button
RA.onEvent("Click", React)
...
ControlClick RA ;Clicks the RA radio button
--- THIS PRECAUTION HOLDS FOR COMBINING FUNCTIONS ANYWHERE IN AHK ---
Moderator's Note: Moved from Scripts and Functions to Tips and Tricks