Syntax
Success = WidgetSetUserData(Widget, *UserData)
Description
Associates a user-defined data pointer with the specified widget. This allows attaching custom data (like pointers to structures or objects) to a widget.
Parameters
Widget
The handle of the ProGUI widget.
*UserData
A pointer to the user data to associate with the widget. Can be any
pointer value (e.g., obtained with `@MyStructure`, `@MyObject`, or `AllocateMemory()`). Set to
#Null to remove existing user data.
Return Value
Returns #True if the user data was successfully associated, or #False if the
widget handle was invalid.
Remarks
This function provides a way to link application-specific data directly to a UI element. The stored pointer can be retrieved later using WidgetGetUserData(), typically within event handlers, to access context without using global variables. ProGUI does not manage the memory pointed to by `*UserData`; the application is responsible for allocating and freeing it appropriately.
Example
IncludeFile "ProGUI_PB.pbi"
StartProGUI()
Structure MyWidgetInfo
ID.i
Description$
EndStructure
; Event handler using UserData
Procedure ShowInfoHandler(Widget, EventType, *EventData, *UserData)
If EventType = #PG_Event_MouseLeftButtonDown
*widgetUserData.MyWidgetInfo = WidgetGetUserData(Widget)
If *widgetUserData ; Check if UserData is valid
Debug "--- Widget Info ---"
Debug "Retrieved Pointer: " + Str(*widgetUserData)
Debug "ID: " + Str(*widgetUserData\ID)
Debug "Description: " + *widgetUserData\Description$
Else
Debug "No user data associated with this widget."
EndIf
EndIf
EndProcedure
MyWindow = CreateWindow(0, 0, 300, 200, "Set User Data Example")
RootLayout = WindowGetLayout(MyWindow)
LayoutSetPadding(RootLayout, 10)
If MyWindow
; Allocate memory for user data
*Info1.MyWidgetInfo = AllocateStructure(MyWidgetInfo)
*Info1\ID = 201
*Info1\Description$ = "This is widget one's data."
*Info2.MyWidgetInfo = AllocateStructure(MyWidgetInfo)
*Info2\ID = 202
*Info2\Description$ = "Data for the second widget."
; Create widget and set user data *after* creation
Widget1 = CreateWidget(0, 0, 150, 40)
WidgetSetClass(Widget1, "button")
WidgetSetUserData(Widget1, *Info1) ; Assign data
AddEventHandler(Widget1, #PG_Event_MouseLeftButtonDown, @ShowInfoHandler())
; Create widget passing user data directly
Widget2 = CreateWidget(0, 50, 150, 40, *Info2)
WidgetSetClass(Widget2, "button")
AddEventHandler(Widget2, #PG_Event_MouseLeftButtonDown, @ShowInfoHandler())
WindowShow(MyWindow, #True, #PG_Window_ScreenCentered)
Repeat
Event = WaitWindowEvent()
Until Event = #PB_Event_CloseWindow
; Clean up allocated memory when done
FreeStructure(*Info1)
FreeStructure(*Info2)
EndIf
StopProGUI()
See Also
WidgetGetUserData, CreateWidget, AddEventHandler
Supported OS
Windows, Linux