### Initialize Cube Mesh Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Mesh.txt Initial setup code for creating a cube mesh. ```PureBasic InitEngine3D() InitSprite() OpenWindow(0, 0, 0, 640, 480, "Cube example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) OpenWindowedScreen(WindowID(0), 0, 0, 640, 480, 0, 0, 0) ; Light ``` -------------------------------- ### Example Usage (Windows) Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Reference/ide_commandline.txt An example demonstrating how to launch PureBasic with the /PORTABLE option to use a portable configuration. ```bash PureBasic.exe Example.pb /PORTABLE ``` -------------------------------- ### SkyDome Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Engine3D.txt An example demonstrating the initialization of the 3D engine, camera setup, loading a sky texture, creating a SkyDome, and rendering the scene. It includes basic input handling for quitting the application. ```purebasic #EndDistance = 1024*4 InitEngine3D() : InitSprite() : InitKeyboard() ExamineDesktops() : dx = DesktopWidth(0)*0.9 : dy = DesktopHeight(0)*0.9 OpenWindow(0, 0, 0, DesktopUnscaledX(dx), DesktopUnscaledY(dy), "SkyDome - Press ESC to quit", #PB_Window_ScreenCentered) OpenWindowedScreen(WindowID(0), 0, 0, dx, dy, 0, 0, 0) Add3DArchive(#PB_Compiler_Home + "examples/3d/Data/Textures", #PB_3DArchive_FileSystem) Parse3DScripts() ; Camera CreateCamera(0, 0, 0, 100, 100) MoveCamera(0,0,5,0) CameraLookAt(0,2,5,10) ; Sky TextureSky = LoadTexture(#PB_Any,"sky.png") SkyDome(TextureID(TextureSky), $cc6600, $0088ff, 3, 400, -0.5, 0) ; Sun CreateLight(0, $ff88ff, 20000, 40000, 20000) AmbientColor($010101) Fog($554488,1, 0, #EndDistance) Repeat While WindowEvent() : Wend ExamineKeyboard() RenderWorld() FlipBuffers() Until KeyboardReleased(#PB_Key_Escape) ``` -------------------------------- ### Link to an example file Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/DocMaker-Tags.html Adds a link to a PureBasic .pb file located in the Examples directory, specifying the target OS. ```PureBasic @ExampleFile All 2DDrawing.pb ``` -------------------------------- ### Extended Example with Keyboard Shortcuts Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Window.txt Demonstrates creating menus and pop-up menus with associated keyboard shortcuts. This example shows how to set up 'Open' with Ctrl+O and 'Copy' with Ctrl+Shift+C. ```PureBasic #Window = 0 Enumeration Menu #Menu #PopupMenu EndEnumeration Enumeration Menu_items #mOpen #mCopy #mDummy EndEnumeration If OpenWindow(#Window, 200, 200, 200, 100, "Press Ctrl+D") If CreateMenu(#Menu, WindowID(#Window)) ; Create a regular menu with title and one item MenuTitle("File") MenuItem(#mOpen, "Open" + #TAB$ + "Ctrl+O") EndIf If CreatePopupMenu(#PopupMenu) ; Create an additional pop-up menu MenuItem(#mCopy, "Copy" + #TAB$ + "Ctrl+Shift+C") EndIf ``` -------------------------------- ### Start Explorer Tool (Windows) Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Reference/ide_commandline.txt Use the /E option to start the Explorer tool and initialize it with the given path. ```bash /E ``` -------------------------------- ### Scale Entity Examples in PureBasic Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Entity.txt Examples demonstrating how to scale entities to double size, maintain current size, change width, and reset size. ```purebasic ScaleEntity(0, 2, 2, 2) ; Double the current size of the entity ``` ```purebasic ScaleEntity(0, 1, 1, 1) ; Don't change the size of the entity (multiply by 1 don't change anything ``` ```purebasic ScaleEntity(0, 3, 1, 1) ; Make the width of the entity 3 times larger ``` ```purebasic ScaleEntity(0, 1, 1, 1, #PB_Absolute) ; Reset the entity size to 1,1,1. ``` -------------------------------- ### Start Explorer Tool (Linux/Mac) Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Reference/ide_commandline.txt Use the -e or --explorerpath option to start the Explorer tool and initialize it with the given path. ```bash -e or --explorerpath ``` -------------------------------- ### Write Preference String Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Preference.txt This example demonstrates how to create a preference file, write string values for keys, and then read those keys back. It shows the usage of CreatePreferences, WritePreferenceString, OpenPreferences, ExaminePreferenceKeys, PreferenceKeyName, and ClosePreferences. Ensure that keys are unique when using #PB_Preference_NoSpace. ```purebasic ; Create a 'ColorList.ini' preference file ; Note: In this case the data values must be unique (no duplicate keys). If CreatePreferences(GetTemporaryDirectory()+"ColorList.ini", #PB_Preference_NoSpace) WritePreferenceString("FF0000", "") WritePreferenceString("00FF00", "") WritePreferenceString("0000FF", "") WritePreferenceString("FF00FF", "") ClosePreferences() Else Debug "Error: Can't create the 'ColorList.ini' file!" EndIf ; Read the 'ColorList.ini' file and output the keys (which are the data here) If OpenPreferences(GetTemporaryDirectory()+"ColorList.ini") ExaminePreferenceKeys() While NextPreferenceKey() Debug PreferenceKeyName() Wend ClosePreferences() Else Debug "Error: Can't read the 'ColorList.ini' file!" EndIf ``` -------------------------------- ### CreateThread Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Thread.txt Demonstrates the basic usage of CreateThread to start a new thread. The procedure used as a thread must accept one parameter and cannot return a value. ```purebasic Procedure YourProcedure(*Value) ; The variable '*Value' will contain 23 EndProcedure CreateThread(@YourProcedure(), 23) ``` -------------------------------- ### ExplorerListGadget Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget.txt A basic example demonstrating how to create and use an ExplorerListGadget. ```APIDOC ## ExplorerListGadget Example ### Description This example shows how to open a window and create an ExplorerListGadget with multi-select enabled. ### Code ```purebasic If OpenWindow(0, 0, 0, 400, 200, "ExplorerListGadget", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) ExplorerListGadget(0, 10, 10, 380, 180, "*.*", #PB_Explorer_MultiSelect) Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf ``` ``` -------------------------------- ### WebGadget Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget.txt A basic example demonstrating how to create and use a WebGadget. ```APIDOC ## WebGadget Example ### Basic Usage ```purebasic If OpenWindow(0, 0, 0, 600, 300, "WebGadget", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) WebGadget(0, 10, 10, 580, 280, "https://www.purebasic.com") ; For local files, use "file://" + path + filename Repeat Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf ``` ``` -------------------------------- ### DocMaker Tag: @ExampleFile Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/DocMaker-Tags.html Adds a link to a PureBasic .pb code example file located in the Examples directory. ```APIDOC ## @ExampleFile ### Description Adds a link to a PureBasic .pb code example in the "Examples" directory. ### Parameters - **target OS** (string) - Required - The target operating system (e.g., All, Windows, Linux). - **filename** (string) - Required - The name of the .pb file. ### Request Example @ExampleFile All 2DDrawing.pb ``` -------------------------------- ### PureBasic Example: Reading a Local Text File Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/File.txt Demonstrates how to use @@OpenFileRequester to select a local text file and then @@ReadFile to open and read its content. The example reads and debugs the first 10 lines of the selected file. ```purebasic Procedure ReadCallback(Status, Filename$, File, Size) If Status = #PB_Status_Loaded Debug "File: " + Filename$ + " - Size: " + Size + " bytes" ; Read the first 10 lines ; While Eof(0) = 0 And NbLine < 10 Debug ReadString(0) NbLine+1 Wend CloseFile(0) ElseIf Status = #PB_Status_Error Debug "Error when loading the file: " + Filename$ EndIf EndProcedure Procedure OpenFileRequesterCallback() If NextSelectedFile() OpenFile(0, SelectedFileID(), @ReadCallback(), #PB_LocalFile) EndIf EndProcedure Procedure ChooseFileEvent() OpenFileRequester("*.txt", @OpenFileRequesterCallback()) EndProcedure OpenWindow(0, 0, 0, 300, 50, "Read file example", #PB_Window_ScreenCentered) ButtonGadget(0, 10, 10, 280, 30, "Choose a file...") BindGadgetEvent(0, @ChooseFileEvent()) ``` -------------------------------- ### Define a code example block Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/DocMaker-Tags.html Use these tags to mark the start and end of a code example section. The content is displayed in a fixed-font size. ```PureBasic @Code Debug "Test" @EndCode ``` -------------------------------- ### Manage App Products in PureBasic Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/InAppPurchase.txt Example showing how to fetch, register, and handle purchase callbacks for app products. ```PureBasic Procedure OnFetchAppProducts(Success) If Success If ExamineAppProducts() While NextAppProduct() Debug "id: " + AppProductId() + ", name: " + AppProductName() + ", price: " + AppProductPrice() Wend Else Debug "ExamineAppProducts() failed." EndIf Else Debug "FetchAppProducts() failed." EndIf EndProcedure Procedure OnPurchaseAppProduct(State, ProductId$) Debug "Product: " + ProductId$ + ", state : " + State EndProcedure RegisterAppProduct("gems", @OnPurchaseAppProduct()) ; can be purchased more than once RegisterAppProduct("helmet", @OnPurchaseAppProduct(), #PB_Product_NonConsumable) ; can be purchased only once FetchAppProducts(@OnFetchAppProducts()) ``` -------------------------------- ### GET ProgramRunning Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Process.txt Tests if a previously started program is still running. ```APIDOC ## GET ProgramRunning ### Description Tests if the specified program is still running. ### Parameters #### Query Parameters - **Program** (Integer) - Required - The program handle returned by RunProgram. ### Response - **Result** (Integer) - Nonzero if the program is running, zero otherwise. ``` -------------------------------- ### PureBasic Compiler Communication Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/PureBasicIDE/sdk/CompilerInterface.html Demonstrates a typical communication sequence with the PureBasic compiler, including starting, compiling, handling errors, and ending the session. This example is specific to Windows. ```text ->STARTING4.10PureBasic 4.10 (Windows - x86) ->READY SOURCEC:\\Temp\\TempFile.pb INCLUDEPATHC:\\SourcePath\\ COMPILEDEBUGGERXPSKINONERROR ->ERRORSYNTAX5 ->INCLUDEFILE25C:\\SourcePath\\Includes.pb ->MESSAGEIncorrect number of parameters. ->OUTPUTCOMPLETE END ``` -------------------------------- ### Load Sound File Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Sound.txt This snippet shows the basic structure for initializing the sound system, enabling OGG decoding, and loading a sound file. It includes error handling for sound system initialization and file loading. ```purebasic If InitSound() ; Initialize Sound system UseOGGSoundDecoder() ; Use ogg files ; Loads a sound from a file ``` -------------------------------- ### Get Mail Body Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Mail.txt Retrieves and displays the body of an email. Ensure an email is available at the specified index. ```PureBasic Debug GetMailBody(0) ; Will print "This is the body" ``` -------------------------------- ### Setup Build Environment on Windows (Official Method) Source: https://github.com/fantaisie-software/purebasic/blob/devel/BUILD.md Run this script to set up the build environment for PureBasic projects on Windows, requiring GnuWin utilities. ```bash BuildEnv.cmd ``` -------------------------------- ### Get Active Gadget in PureBasic Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/MainGuide/changes.txt Use GetActiveGadget() to retrieve the currently active gadget. This function does not require any setup. ```purebasic ActiveGadget.i = GetActiveGadget() ``` -------------------------------- ### Get File Pointer Position with Loc Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/File.txt Retrieve the current read/write pointer position in bytes relative to the start of the file. ```PureBasic If CreateFile(0, "Text.txt") ; we create a new text file WriteString(0, "Hello world") Debug Loc(0) ; will print '11' FileSeek(0, 2, #PB_Absolute) ; Change the file pointer position Debug Loc(0) ; will print '2' CloseFile(0) EndIf ``` -------------------------------- ### Full Example: Linear Gradient with Different Colors - PureBasic Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/2DDrawing.txt Illustrates setting a linear gradient with different start and end colors, then drawing circles. This example showcases overriding default gradient colors. Requires DrawingMode(#PB_2DDrawing_Gradient) and ImageOutput or CanvasOutput. ```PureBasic If OpenWindow(0, 0, 0, 400, 200, "2DDrawing Example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) If CreateImage(0, 400, 200) And StartDrawing(ImageOutput(0)) Box(0, 0, 400, 200, $FFFFFF) DrawingMode(#PB_2DDrawing_Gradient) BackColor($00FFFF) FrontColor($FF0000) LinearGradient(0, 0, 200, 200) Circle(100, 100, 100) LinearGradient(350, 100, 250, 100) Circle(300, 100, 100) StopDrawing() ImageGadget(0, 0, 0, 400, 200, ImageID(0)) EndIf Repeat Event = WaitWindowEvent() Until Event = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Register and Fetch App Products Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/InAppPurchase.txt Demonstrates registering two products ('gems' as consumable and 'helmet' as non-consumable) with a shared purchase callback, then fetching their details using FetchAppProducts and processing the results. ```PureBasic Procedure OnFetchAppProducts(Success) If Success If ExamineAppProducts() While NextAppProduct() Debug "id: " + AppProductId() + ", name: " + AppProductName() + ", price: " + AppProductPrice() Wend Else Debug "ExamineAppProducts() failed." EndIf Else Debug "FetchAppProducts() failed." EndIf EndProcedure Procedure OnPurchaseAppProduct(State, ProductId$) Debug "Product: " + ProductId$ + ", state : " + State EndProcedure RegisterAppProduct("gems", @OnPurchaseAppProduct()) ; can be purchased more than once RegisterAppProduct("helmet", @OnPurchaseAppProduct(), #PB_Product_NonConsumable) ; can be purchased only once FetchAppProducts(@OnFetchAppProducts()) ``` -------------------------------- ### Setup Build Environment on Linux Source: https://github.com/fantaisie-software/purebasic/blob/devel/BUILD.md Execute this script to set up the build environment for PureBasic projects on Linux, providing the path to your PureBasic installation. ```bash ./BuildEnv.sh ``` -------------------------------- ### Initialize a WebGadget Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget.txt Demonstrates the basic setup of a window containing a WebGadget pointing to a URL. ```PureBasic If OpenWindow(0, 0, 0, 600, 300, "WebGadget", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) WebGadget(0, 10, 10, 580, 280, "https://www.purebasic.com") ; Note: if you want to use a local file, change last parameter to "file://" + path + filename Repeat Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Get X Coordinate of a Point on a Vector Path Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/VectorDrawing.txt PathPointX returns the X coordinate of a point at a specified distance from the start of the current vector drawing path. If the distance is out of bounds, the start or endpoint is returned. Use PathLength to determine the total path length. ```PureBasic x = PathPointX(200) y = PathPointY(200) a = PathPointAngle(200) ; stroke the path VectorSourceColor(RGBA(255, 0, 0, 255)) StrokePath(5) ; draw a marker at the path point AddPathCircle(x, y, 10) VectorSourceColor(RGBA(0, 0, 255, 255)) FillPath() MovePathCursor(x, y) AddPathLine(30*Cos(Radian(a)), 30*Sin(Radian(a)), #PB_Path_Relative) StrokePath(5) ``` -------------------------------- ### Create Menu Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Menu.txt Demonstrates creating a menu bar with titles and menu items, including items with underlined characters and separate shortcut text. ```purebasic If OpenWindow(0, 200, 200, 200, 100, "MenuItem Example") If CreateMenu(0, WindowID(0)) MenuTitle("Project") MenuItem(1, "Open") ; normal item MenuItem(2, "&Save") ; item with underlined character, the underline will only ; be displayed, if menu is called with F10 + arrow keys MenuItem(3, "Quit"+Chr(9)+"Esc") ; item with separate shortcut text EndIf Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Get Any JSON Value Type Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/Json.txt This procedure demonstrates how to handle and retrieve values of any JSON type. It requires no specific setup beyond the JSON parsing itself. ```PureBasic Procedure.s GetAnyValue(Value) Select JSONType(Value) Case #PB_JSON_Null: ProcedureReturn "null" Case #PB_JSON_String: ProcedureReturn GetJSONString(Value) Case #PB_JSON_Number: ProcedureReturn StrD(GetJSONDouble(Value)) Case #PB_JSON_Boolean: ProcedureReturn Str(GetJSONBoolean(Value)) Case #PB_JSON_Array: ProcedureReturn "array" Case #PB_JSON_Object: ProcedureReturn "object" EndSelect EndProcedure ParseJSON(0, "[1, 2, true, null, " + Chr(34) + "hello" + Chr(34) + "]") For i = 0 To JSONArraySize(JSONValue(0)) - 1 Debug GetAnyValue(GetJSONElement(JSONValue(0), i)) Next i ``` -------------------------------- ### Create and Populate a ListViewGadget Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/Gadget.txt Demonstrates initializing a window, creating a list view, adding items, and setting the active selection. ```PureBasic If OpenWindow(0, 0, 0, 270, 140, "ListViewGadget", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) ListViewGadget(0, 10, 10, 250, 120) For a = 1 To 12 AddGadgetItem (0, -1, "Item " + Str(a) + " of the Listview") ; define listview content Next SetGadgetState(0, 4) ; set (beginning with 0) the fifth item as the active one EndIf ``` -------------------------------- ### Apply and Configure Screen Shaders Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/Screen.txt Demonstrates initializing a screen, registering event callbacks for loading and rendering, and applying a reflection shader with attribute adjustments. ```PureBasic OpenScreen(800, 600, 32, "Shader Test") SetFrameRate(60) Procedure RenderFrame() Static Time.d DisplaySprite(0, 0, 0) ; Animate the reflection wave Time + 0.05 ScreenShaderAttribute(#PB_ReflectionShader_Time, Time) FlipBuffers() ; continue the rendering EndProcedure Procedure Loading(Type, Filename$) Static NbLoadedElements NbLoadedElements+1 If NbLoadedElements = 1 ; Finished the loading of all images and sounds, we can start the applications AddScreenShader(#PB_Shader_Reflection) ScreenShaderAttribute(#PB_ReflectionShader_Boundary, 0.80) FlipBuffers() ; start the rendering EndIf EndProcedure Procedure LoadingError(Type, Filename$) Debug Filename$ + ": loading error" EndProcedure ; Register the loading event before calling any resource load command BindEvent(#PB_Event_Loading, @Loading()) BindEvent(#PB_Event_LoadingError, @LoadingError()) BindEvent(#PB_Event_RenderFrame, @RenderFrame()) LoadSprite(0, "Data/Mountain.jpg") ``` -------------------------------- ### Get Active Gadget Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget.txt Demonstrates how to find the gadget with keyboard focus and display its number when an escape shortcut is pressed. Ensure the window and gadgets are created before calling this function. ```PureBasic If OpenWindow(0, 0, 0, 270, 70, "GetActiveGadget", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) StringGadget (0, 10, 10, 250, 20, "Press escape...") StringGadget (1, 10, 40, 250, 20, "Press escape...") AddKeyboardShortcut(0, #PB_Shortcut_Escape, 1) SetActiveGadget(0) Repeat Event = WaitWindowEvent() If Event = #PB_Event_Menu And EventMenu() = 1 MessageRequester("Test", "Escape pressed in Gadget " + Str(GetActiveGadget())) EndIf Until Event = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Start Drawing on a Sprite Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Sprite.txt Use SpriteOutput() to get the drawing ID for a sprite. This ID is then passed to StartDrawing() to begin rendering operations on the sprite. Ensure StartDrawing() and StopDrawing() calls are paired. ```purebasic StartDrawing(SpriteOutput(#Sprite)) ; do some drawing stuff here... StopDrawing() ``` -------------------------------- ### Create and Configure a StatusBar Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/StatusBar.txt Demonstrates initializing a window, creating a status bar, adding fields with varying widths, and setting text content with different alignments. ```PureBasic If OpenWindow(0, 0, 0, 440, 50, "StatusBar", #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_SizeGadget) If CreateStatusBar(0, WindowID(0)) AddStatusBarField(90) AddStatusBarField(100) AddStatusBarField(#PB_Ignore) ; automatically resize this field AddStatusBarField(100) EndIf StatusBarText(0, 0, "Area normal") StatusBarText(0, 1, "Area borderless", #PB_StatusBar_BorderLess) StatusBarText(0, 2, "Area right", #PB_StatusBar_Right) StatusBarText(0, 3, "Area centered", #PB_StatusBar_Center) Repeat Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Create a Toolbar with Buttons Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Toolbar.txt Demonstrates initializing a window, creating a toolbar, and adding image buttons to it. ```PureBasic If OpenWindow(0, 0, 0, 150, 25, "ToolBar", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) If CreateToolBar(0, WindowID(0)) UsePNGImageDecoder() Path$ = #PB_Compiler_Home + "Examples" + #PS$ + "Sources" + #PS$ + "Data" + #PS$ + "ToolBar" + #PS$ + "" ToolBarImageButton(0, LoadImage(0, Path$ + "New.png")) ToolBarImageButton(1, LoadImage(1, Path$ + "Open.png")) ToolBarImageButton(2, LoadImage(2, Path$ + "Save.png")) EndIf Repeat Event = WaitWindowEvent() If Event = #PB_Event_Menu Debug "ToolBar ID: "+Str(EventMenu()) EndIf Until Event = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Set and Use Packer Callback for Compression Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Packer.txt This example demonstrates how to set a callback function using PackerCallback() to monitor the compression progress of memory. The callback is installed globally and will be invoked during CompressMemory(). ```purebasic UseZipPacker() ; The callback will be called at regular intervall, to allow to display ; some progress or abort the compression. It must match the following declaration. ; Procedure Callback(Current.q, Total.q) Debug "Progress: " + Current + " bytes / "+ Total + " bytes" ProcedureReturn #True ; Returns #True to continue to compress, or #False to abort EndProcedure ; Install the callback for all the future packer compression PackerCallback(@Callback()) ; Allocate 50 GB of memory to compress it *Buffer = AllocateMemory(50*1024*1024, #PB_Memory_NoClear) ; The output buffer a bit bigger than source, just in case *Output = AllocateMemory(51*1024*1024, #PB_Memory_NoClear) CompressedSize = CompressMemory(*Buffer, MemorySize(*Buffer), *Output, MemorySize(*Output)) Debug "Compressed length: " + CompressedSize + " bytes" ``` -------------------------------- ### Get Program Process ID (PID) Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Process.txt Retrieves the unique system identifier (Process ID or PID) for a program started with RunProgram. Returns -1 if the identifier cannot be obtained, such as when opening a file with RunProgram. ```PureBasic Result = ProgramID(Program) ``` -------------------------------- ### Open File Requester Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Requester.txt Demonstrates how to open a file selection dialog with specific file patterns and handle the user's selection. ```PureBasic StandardFile$ = "C:\autoexec.bat" ; set initial file+path to display ; With next string we will set the search patterns ("|" as separator) for file displaying: ; 1st: "Text (*.txt)" as name, ".txt" and ".bat" as allowed extension ; 2nd: "PureBasic (*.pb)" as name, ".pb" as allowed extension ; 3rd: "All files (*.*) as name, "*.*" as allowed extension, valid for all files Pattern$ = "Text (*.txt;*.bat)|*.txt;*.bat|PureBasic (*.pb)|*.pb|All files (*.*)|*.*" Pattern = 0 ; use the first of the three possible patterns as standard File$ = OpenFileRequester("Please choose file to load", StandardFile$, Pattern$, Pattern) If File$ MessageRequester("Information", "You have selected following file:" + Chr(10) + File$, 0) Else MessageRequester("Information", "The requester was canceled.", 0) EndIf ``` -------------------------------- ### Get Macro Expansion Count in PureBasic Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Reference/macros.txt Demonstrates the use of 'MacroExpandedCount' to retrieve the number of times a macro has been expanded. This can be useful for generating unique identifiers within macros. The example calls a macro multiple times to show the incrementing count. ```PureBasic Macro Test Debug MacroExpandedCount EndMacro Test ; Call the macro Test ; Call the macro Test ; Call the macro ``` -------------------------------- ### Get Program Filename Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Process.txt Returns the full path and filename of the currently executing program. Useful for locating the program's installation or executable name. If used within a DLL, it returns the DLL's path, not the main program's. ```PureBasic Result$ = ProgramFilename() ``` -------------------------------- ### Send String via WebSocket and Handle String Events Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/WebSocket.txt Shows how to send a string over an established WebSocket connection and handle incoming string data. This example also includes basic UI setup and event binding for both gadget and WebSocket events. ```purebasic Procedure Events() Select Event() Case #PB_Event_Gadget Select EventGadget() Case 0 ; The server will send back the same string, so we should ; get it in the #PB_Event_WebSocket event SendWebSocketString(2, "Hello !") EndSelect Case #PB_Event_WebSocket Select EventType() Case #PB_EventType_Connected Debug "WebSocket #" + EventWebSocket() + " connected." Case #PB_EventType_Closed Debug "WebSocket #" + EventWebSocket() + " closed." Case #PB_EventType_String Debug "String received on WebSocket #" + EventWebSocket() + "." Debug "String content: " + EventString() Case #PB_EventType_Error Debug "Error on WebSocket #" + EventWebSocket() + "." EndSelect EndSelect EndProcedure BindEvent(#PB_Event_Gadget, @Events()) BindEvent(#PB_Event_WebSocket, @Events()) OpenWindow(0, 100, 100, 220, 50, "WebSocket test") ButtonGadget(0, 10, 10, 200, 30, "Send string !") ; Connect to a free online WebSocket which sends back every command If OpenWebSocket(2, "wss://ws.postman-echo.com/raw") Debug "Trying to open the WebSocket" Else Debug "WebSocket not supported." EndIf ``` -------------------------------- ### Reference NetworkClient.pb Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Network.txt Example file demonstrating client-side network operations. ```PureBasic All NetworkClient.pb ``` -------------------------------- ### Example: Create Mesh LOD Levels Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Mesh.txt Demonstrates creating multiple LOD levels for a mesh with specified distances and reduction values. The first reduction starts at 100 units, halving vertices by 4, with subsequent reductions calculated based on distance and reduction value. ```purebasic CreateMeshLodLevels(@#Mesh, 3, 100, 0.75) ``` -------------------------------- ### Open a windowed screen with gadgets Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/Screen.txt Demonstrates initializing a window and attaching a screen area to it using OpenWindowedScreen, including a rendering loop triggered by BindEvent. ```PureBasic OpenWindow(0, 20, 20, 840, 640, "A screen in a window...", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) OpenWindowedScreen(WindowID(0), 20, 20, 800, 600) Procedure RenderFrame() Static x, y ClearScreen(RGB(0, 0, 0)) x+1 DisplaySprite(0, x, 30) FlipBuffers() ; continue the rendering EndProcedure ; Register the render event so FlipBuffers() will trigger the associated procedure BindEvent(#PB_Event_RenderFrame, @RenderFrame()) CreateSprite(0, 64, 64) If StartDrawing(SpriteOutput(0)) Circle(32, 32, 25, RGB(255, 0, 0)) ; Red circle StopDrawing() EndIf FlipBuffers() ; trigger the rendering ``` -------------------------------- ### Open help files with OpenHelp Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Help.txt Displays a help window using a specified filename and optional topic page. Note that this command is not supported by the QT subsystem. ```PureBasic OpenHelp("help.chm", "index.htm") OpenHelp("help.chm", "print.txt") ``` -------------------------------- ### Create GUI Window and Gadgets in PureBasic Source: https://context7.com/fantaisie-software/purebasic/llms.txt Demonstrates window creation, adding various gadgets like panels and lists, and handling events in a loop. ```purebasic ; Window creation with standard gadgets #WindowWidth = 400 #WindowHeight = 300 If OpenWindow(0, 100, 100, #WindowWidth, #WindowHeight, "PureBasic GUI", #PB_Window_SystemMenu | #PB_Window_MinimizeGadget) ; Create various gadgets StringGadget(0, 10, 10, 200, 25, "Enter text here") ButtonGadget(1, 220, 10, 80, 25, "Click Me") ; Panel with multiple tabs PanelGadget(2, 10, 45, #WindowWidth-20, 200) AddGadgetItem(2, 0, "Options") CheckBoxGadget(3, 10, 10, 150, 25, "Enable feature") ComboBoxGadget(4, 10, 40, 150, 25) AddGadgetItem(4, -1, "Option 1") AddGadgetItem(4, -1, "Option 2") SetGadgetState(4, 0) OptionGadget(5, 10, 70, 100, 25, "Choice A") OptionGadget(6, 10, 95, 100, 25, "Choice B") SetGadgetState(5, 1) AddGadgetItem(2, 1, "List") ListViewGadget(7, 10, 10, 200, 150) For i = 0 To 10 AddGadgetItem(7, -1, "Item " + Str(i)) Next CloseGadgetList() TextGadget(8, 10, #WindowHeight-30, 200, 20, "Status: Ready") ; Event loop Repeat Event = WaitWindowEvent() If Event = #PB_Event_Gadget Select EventGadget() Case 1 ; Button clicked SetGadgetText(8, "Button clicked!") Case 7 ; ListView selection If EventType() = #PB_EventType_LeftDoubleClick SetGadgetText(0, GetGadgetText(7)) EndIf EndSelect EndIf Until Event = #PB_Event_CloseWindow EndIf ``` -------------------------------- ### Dynamically Resize Gadgets with Window Size Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget.txt This example shows how to resize gadgets in real-time as the window dimensions change. Use #PB_Ignore to keep specific gadget dimensions unchanged during resizing. ```purebasic Procedure SizeHandler() ResizeGadget(0, #PB_Ignore, #PB_Ignore, WindowWidth(0) - 20, WindowHeight(0) - 60) ResizeGadget(1, #PB_Ignore, WindowHeight(0) - 40, WindowWidth(0) - 20, #PB_Ignore) EndProcedure If OpenWindow(0, 0, 0, 220, 100, "Resize the window", #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_SizeGadget) WindowBounds(0, WindowWidth(0), WindowHeight(0), #PB_Ignore, #PB_Ignore) EditorGadget(0, 10, 10, WindowWidth(0) - 20, WindowHeight(0) - 60) ButtonGadget(1, 10, WindowHeight(0) - 40, WindowWidth(0) - 20, 30, "Button") ; Use BindEvent() to have a realtime gadget resize BindEvent(#PB_Event_SizeWindow, @SizeHandler()) Repeat Select WaitWindowEvent() Case #PB_Event_CloseWindow End EndSelect ForEver EndIf ``` -------------------------------- ### Get Gadget Attribute Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget3D.txt Gets the attribute value of the specified 3D gadget. ```APIDOC ## GetGadgetAttribute3D #Gadget3D, Attribute ### Description Gets the attribute value of the specified 3D gadget. ### Method Function ### Endpoint N/A (PureBasic function) ### Parameters #### Path Parameters - **#Gadget3D** (number) - Required - The 3D gadget to use. - **Attribute** (string/constant) - Required - The attribute to get. #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response - **ReturnValue** (any) - The attribute value of the specified 3D gadget. #### Response Example ``` "Some Attribute Value" ``` ``` -------------------------------- ### ListIconGadget Usage Examples Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Gadget.txt Provides code examples demonstrating how to create and populate a ListIconGadget. ```APIDOC ## ListIconGadget Usage Examples ### Example 1: Basic ListIconGadget ```purebasic If OpenWindow(0, 100, 100, 300, 100, "ListIcon Example", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) ListIconGadget(0, 5, 5, 290, 90, "Name", 100, #PB_ListIcon_FullRowSelect | #PB_ListIcon_AlwaysShowSelection) AddGadgetColumn(0, 1, "Address", 250) AddGadgetItem(0, -1, "Harry Rannit"+Chr(10)+"12 Parliament Way, Battle Street, By the Bay") AddGadgetItem(0, -1, "Ginger Brokeit"+Chr(10)+"130 PureBasic Road, BigTown, CodeCity") Repeat Event = WaitWindowEvent() Until Event = #PB_Event_CloseWindow EndIf ``` ### Example 2: ListIconGadget with Various Flags ```purebasic ; Shows possible flags of ListIconGadget in action... If OpenWindow(0, 0, 0, 700, 300, "ListIconGadgets", #PB_Window_SystemMenu | #PB_Window_ScreenCentered) ; left column TextGadget (6, 10, 10, 330, 20, "ListIcon Standard", #PB_Text_Center) ListIconGadget(0, 10, 25, 330, 70, "Column 1", 100) TextGadget (7, 10, 105, 330, 20, "ListIcon with Checkbox", #PB_Text_Center) ListIconGadget(1, 10, 120, 330, 70, "Column 1", 100, #PB_ListIcon_CheckBoxes) ; ListIcon with checkbox TextGadget (8, 10, 200, 330, 20, "ListIcon with Multi-Selection", #PB_Text_Center) ListIconGadget(2, 10, 215, 330, 70, "Column 1", 100, #PB_ListIcon_MultiSelect) ; ListIcon with multi-selection ; right column TextGadget (9, 360, 10, 330, 20, "ListIcon with separator lines",#PB_Text_Center) ListIconGadget(3, 360, 25, 330, 70, "Column 1", 100, #PB_ListIcon_GridLines) TextGadget (10, 360, 105, 330, 20, "ListIcon with FullRowSelect and AlwaysShowSelection",#PB_Text_Center) ListIconGadget(4, 360, 120, 330, 70, "Column 1", 100, #PB_ListIcon_FullRowSelect | #PB_ListIcon_AlwaysShowSelection) TextGadget (11, 360, 200, 330, 20, "ListIcon Standard with large icons",#PB_Text_Center) ListIconGadget(5, 360, 220, 330, 65, "", 200,#PB_ListIcon_GridLines) For a = 0 To 4 ; add columns to each of the first 5 listicons For b = 2 To 4 ; add 3 more columns to each listicon AddGadgetColumn(a, b, "Column " + Str(b), 65) Next For b = 0 To 2 ; add 4 items to each line of the listicons AddGadgetItem(a, b, "Item 1"+Chr(10)+"Item 2"+Chr(10)+"Item 3"+Chr(10)+"Item 4") Next Next ; Here we change the ListIcon display to large icons and show an image If LoadImage(0, #PB_Compiler_Home+"examples/sources/Data/File.bmp") ; change path/filename to your own 32x32 pixel image SetGadgetAttribute(5, #PB_ListIcon_DisplayMode, #PB_ListIcon_LargeIcon) AddGadgetItem(5, 0, "Picture 1", ImageID(0)) AddGadgetItem(5, 1, "Picture 2", ImageID(0)) EndIf Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow EndIf ``` ``` -------------------------------- ### Path Requester Example Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Requester.txt Demonstrates how to open a directory selection dialog and retrieve the chosen path. ```PureBasic InitialPath$ = "C:\" ; set initial path to display (could also be blank) Path$ = PathRequester("Please choose your path", InitialPath$) If Path$ MessageRequester("Information", "You have selected following path:"+Chr(10)+Path$, 0) Else MessageRequester("Information", "The requester was canceled.", 0) EndIf ``` -------------------------------- ### Initialize Sound System and Play/Manage OGG Files Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/English/Sound.txt Initializes the sound system, uses the OGG sound decoder, loads two OGG sounds, plays the first sound, and retrieves its position in milliseconds. It then plays the second sound and displays a message. ```purebasic If InitSound() ; Initialize Sound system UseOGGSoundDecoder() ; Use ogg files ; Loads 2 sounds If LoadSound(0, #PB_Compiler_Home + "Examples/3D/Data/Siren.ogg") If LoadSound(1, #PB_Compiler_Home + "Examples/3D/Data/Roar.ogg") ; The siren is playing PlaySound(0) ; Display the position Repeat Pos = GetSoundPosition(0, #PB_Sound_Millisecond) Delay(100) ; Wait 100 ms Debug Pos ; Display the position If Pos > 1000 ; Stop after 1 second Break EndIf ForEver ; Then 2 sounds are playing together PlaySound(1) MessageRequester("Info", "Ok to stop.") End EndIf EndIf Else Debug "Warning! The sound environment couldn't be initialized. So no sound commands can be used..." EndIf ``` -------------------------------- ### Start Accelerometer Monitoring Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/Accelerometer.txt Starts the monitoring of accelerometer data at a specified refresh frequency. ```APIDOC ## StartAccelerometer ### Description Starts accelerometer data monitoring. ### Parameters #### Path Parameters - **Frequency** (integer) - Required - The frequency (in milliseconds) to refresh the accelerometer data. The lower the frequency is, the more CPU it consumes. This is a reference value, depending of the device it can lack of precision. @@AccelerometerTime can be used to monitor the delay between 2 different fetches. ### Return Value - **Result** (integer) - Nonzero if accelerometer functions are available (i.e. the device has an accelerometer), zero otherwise. ### See Also - @@StopAccelerometer - @@AccelerometerX - @@AccelerometerY - @@AccelerometerZ - @@AccelerometerTime ``` -------------------------------- ### Create and Configure a ToolBar Source: https://github.com/fantaisie-software/purebasic/blob/devel/Documentation/SpiderBasic/English/Toolbar.txt Demonstrates creating a window, initializing a toolbar with image buttons, and binding menu events to handle toolbar interactions. ```SpiderBasic Procedure MenuEvents() Debug "ToolBar item selected: " + EventMenu() EndProcedure If OpenWindow(0, 0, 0, 295, 260, "ToolBar example", #PB_Window_SystemMenu | #PB_Window_SizeGadget | #PB_Window_ScreenCentered) CreateImage(0, 16, 16, 32, #PB_Image_Transparent) If StartDrawing(ImageOutput(0)) Circle(8, 8, 7, RGB(255, 0, 0)) StopDrawing() EndIf If CreateToolBar(0, WindowID(0)) ToolBarImageButton(0, ImageID(0)) ToolBarImageButton(2, ImageID(0)) ToolBarSeparator() ToolBarImageButton(3, ImageID(0)) ToolBarToolTip(0, 3, "Cut") ToolBarImageButton(4, ImageID(0)) ToolBarToolTip(0, 4, "Copy") EndIf DisableToolBarButton(0, 2, 1) ; Disable the button '2' BindEvent(#PB_Event_Menu, @MenuEvents()) EndIf ```