Examples for Documentation

Found an issue in the documentation ? Please report it here !

Moderator: Documentation Editors

User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 2137
Joined: Fri Apr 25, 2003 6:14 pm
Location: Germany (Saxony, Deutscheinsiedel)
Contact:

Re: Examples for Documentation

Post by Andre »

Added the examples for following commands:
- ChangeSysTrayIcon
- AddSysTrayIcon
- AddKeyboardShortcut

All with additional comments and all in a bit adapted / simplified form, e.g. for ChangeSysTrayIcon I've used a randomly sized red dot on the yellow background.

Again thanks a lot, AZJIO :D
Bye,
...André
(PureBasicTeam::Docs & Support - PureArea.net | Order:: PureBasic | PureVisionXP)
User avatar
Piero
Addict
Addict
Posts: 862
Joined: Sat Apr 29, 2023 6:04 pm
Location: Italy

Re: Examples for Documentation

Post by Piero »

I would like to see some "quick example" of how to use WriteProgramString(N) and #PB_Program_Eof ... :wink:

Code: Select all

Procedure Shell(ShellCommand$, AddReturns = #True)
   Protected Err$, tmper$, Output$, shell, Exc.w = -1 ; -1 on failed launch
   shell = RunProgram("/bin/sh","","",
      #PB_Program_Open|#PB_Program_Write|#PB_Program_Read|#PB_Program_Error )
   If shell
      WriteProgramStringN(shell,ShellCommand$)
      WriteProgramData(shell,#PB_Program_Eof,0)
      While ProgramRunning(shell)
         If AvailableProgramOutput(shell)
            Output$ + ReadProgramString(shell)
            If AddReturns : Output$ + Chr(13) : EndIf
         EndIf
         tmper$ = ReadProgramError(shell)
         If tmper$ : Err$ + tmper$ + Chr(13) : EndIf
      Wend
      Exc = ProgramExitCode(shell) : CloseProgram(shell)
   EndIf
   Sh\Out = Output$ : Sh\Err = Err$ : Sh\ExC = Exc
EndProcedure
AZJIO
Addict
Addict
Posts: 2141
Joined: Sun May 14, 2017 1:48 am

Re: Examples for Documentation

Post by AZJIO »

SaveImage
It took me a while to figure out that I needed to use UsePNGImageEncoder(). The description does not say about it. (on the SaveSprite page, also specify)

Code: Select all

#Image = 0
Define tmp$
UsePNGImageEncoder()

If CreateImage(#Image, 33, 33)
	If StartDrawing(ImageOutput(#Image))
		DrawingMode(#PB_2DDrawing_Transparent)
		Box(0, 0, 33, 33, $FF0000)
		StopDrawing()
	EndIf
	tmp$ = SaveFileRequester("Select file to save", GetCurrentDirectory(), "*.png|*.png", 0)
	If Asc(tmp$)
		tmp$ + ".png"
		If SaveImage(#Image, tmp$, #PB_ImagePlugin_PNG)
			MessageRequester("File created", tmp$)
		Else
			MessageRequester("Error", "Failed to save file")
		EndIf
	EndIf
	FreeImage(#Image)
EndIf
juergenkulow
Enthusiast
Enthusiast
Posts: 581
Joined: Wed Sep 25, 2019 10:18 am

Re: Examples for Documentation

Post by juergenkulow »

AZJIO
Addict
Addict
Posts: 2141
Joined: Sun May 14, 2017 1:48 am

Re: Examples for Documentation

Post by AZJIO »

ProgramParameter() (version 2)
The most practical and elementary example. After all, it is often necessary to open a file in the program.

Code: Select all

Define path$, Text$

If OpenWindow(0, 0, 0, 520, 510, "Example...", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
	EditorGadget(0, 5, 5, 510, 500, #PB_Editor_WordWrap)
	path$ = ProgramParameter()
	If Asc(path$) And FileSize(path$) >= 0
		If ReadFile(0, path$)
			Text$ = ReadString(0, #PB_File_IgnoreEOL)
		EndIf
		SetGadgetText(0, Text$)
	EndIf
	Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf
juergenkulow
Enthusiast
Enthusiast
Posts: 581
Joined: Wed Sep 25, 2019 10:18 am

Re: Examples for Documentation

Post by juergenkulow »

UsePNGImageDecoder

Code: Select all

; Select and show PNG File until ALT-F4 is pressed. 
UsePNGImageDecoder() ;Activates support for PNG images, here for LoadImage in line 9. 
ExamineDesktops()    ;Determine information about the screens the number of pixels, 
                     ;here For DesktopHeight And DesktopWidth.  
#screen=0            ;Select a screen.
File$ = OpenFileRequester("Select PNG", #PB_Compiler_Home+"logo.png",
                          "PNG Picture (*.png)|*.png|Alle Dateien (*.*)|*.*",0) ;Select a file.
If File$<>""         ;If a file has been selected.
  image=LoadImage(#PB_Any,File$)   ;Load the specified image from the file with the name File$.
  Width=ImageWidth(image)          ;Determine the width in pixels of image.
  Height=ImageHeight(image)        ;Determine the width in pixels of image.
  If Width>DesktopWidth(#screen) Or Height>DesktopHeight(#screen) ;If the image is larger than the screen.
    Width=DesktopWidth(#screen)    ;The width becomes the width of the selected screen and 
    Height=DesktopHeight(#screen)  ;the height becomes the height of the selected screen.
  EndIf
  OpenWindow(0,0,0,Width/DesktopResolutionX(),Height/DesktopResolutionY(),"ShowPNG",#PB_Window_BorderLess) 
                                   ;Open a window without a frame in the top left-hand corner.
  ImageGadget(0,0,0,Width,Height,ImageID(image));Create an image gadget in the top left-hand corner of the window.
  Repeat
  Until WaitWindowEvent()=#PB_Event_CloseWindow ;Waits until an event occurs. When ALT-F4 is pressed, 
                                                ;end the loop and exit the program.
EndIf 
Documentation ImagePlugin.txt Line 156
User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 2137
Joined: Fri Apr 25, 2003 6:14 pm
Location: Germany (Saxony, Deutscheinsiedel)
Contact:

Re: Examples for Documentation

Post by Andre »

AZJIO wrote: Tue Nov 21, 2023 2:47 pm SaveImage
It took me a while to figure out that I needed to use UsePNGImageEncoder(). The description does not say about it. (on the SaveSprite page, also specify)

Code: Select all

#Image = 0
Define tmp$
UsePNGImageEncoder()

If CreateImage(#Image, 33, 33)
	If StartDrawing(ImageOutput(#Image))
		DrawingMode(#PB_2DDrawing_Transparent)
		Box(0, 0, 33, 33, $FF0000)
		StopDrawing()
	EndIf
	tmp$ = SaveFileRequester("Select file to save", GetCurrentDirectory(), "*.png|*.png", 0)
	If Asc(tmp$)
		tmp$ + ".png"
		If SaveImage(#Image, tmp$, #PB_ImagePlugin_PNG)
			MessageRequester("File created", tmp$)
		Else
			MessageRequester("Error", "Failed to save file")
		EndIf
	EndIf
	FreeImage(#Image)
EndIf
I will add a slightly modified example to SaveImage() command:

Code: Select all

  UsePNGImageEncoder()
  
  If CreateImage(0, 33, 33)
    If StartDrawing(ImageOutput(0))
      DrawingMode(#PB_2DDrawing_Transparent)
        Box(0, 0, 33, 33, $FF0000) ; draw a blue box and save it as image file below
      StopDrawing()
    EndIf
    file$ = SaveFileRequester("Select file to save", GetCurrentDirectory(), "*.png|*.png", 0)
    If file$
      If GetExtensionPart(file$) = ""
        file$ + ".png"  ; add the file extension if needed
      EndIf
      If SaveImage(0, file$, #PB_ImagePlugin_PNG)
        MessageRequester("File created", file$)
      Else
        MessageRequester("Error", "Failed to save file")
      EndIf
    EndIf
    FreeImage(0)
  EndIf
Bye,
...André
(PureBasicTeam::Docs & Support - PureArea.net | Order:: PureBasic | PureVisionXP)
User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 2137
Joined: Fri Apr 25, 2003 6:14 pm
Location: Germany (Saxony, Deutscheinsiedel)
Contact:

Re: Examples for Documentation

Post by Andre »

AZJIO wrote: Tue Nov 21, 2023 5:12 pm ProgramParameter() (version 2)
The most practical and elementary example. After all, it is often necessary to open a file in the program.

Code: Select all

Define path$, Text$

If OpenWindow(0, 0, 0, 520, 510, "Example...", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
	EditorGadget(0, 5, 5, 510, 500, #PB_Editor_WordWrap)
	path$ = ProgramParameter()
	If Asc(path$) And FileSize(path$) >= 0
		If ReadFile(0, path$)
			Text$ = ReadString(0, #PB_File_IgnoreEOL)
		EndIf
		SetGadgetText(0, Text$)
	EndIf
	Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf
Thanks, AZJIO! Added it in a slightly simplified version:

Code: Select all

  ; Call the compiled program from command-line with the file to display as parameter
  If OpenWindow(0, 0, 0, 520, 510, "Example...", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
    EditorGadget(0, 5, 5, 510, 500, #PB_Editor_WordWrap)
    path$ = ProgramParameter()
    If FileSize(path$) >= 0
      If ReadFile(0, path$)
        Text$ = ReadString(0, #PB_File_IgnoreEOL)
      EndIf
      SetGadgetText(0, Text$)
    EndIf
    Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
  EndIf
Bye,
...André
(PureBasicTeam::Docs & Support - PureArea.net | Order:: PureBasic | PureVisionXP)
User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 2137
Joined: Fri Apr 25, 2003 6:14 pm
Location: Germany (Saxony, Deutscheinsiedel)
Contact:

Re: Examples for Documentation

Post by Andre »

juergenkulow wrote: Fri Dec 01, 2023 9:44 pm UsePNGImageDecoder

Code: Select all

; Select and show PNG File until ALT-F4 is pressed. 
UsePNGImageDecoder() ;Activates support for PNG images, here for LoadImage in line 9. 
ExamineDesktops()    ;Determine information about the screens the number of pixels, 
                     ;here For DesktopHeight And DesktopWidth.  
#screen=0            ;Select a screen.
File$ = OpenFileRequester("Select PNG", #PB_Compiler_Home+"logo.png",
                          "PNG Picture (*.png)|*.png|Alle Dateien (*.*)|*.*",0) ;Select a file.
If File$<>""         ;If a file has been selected.
  image=LoadImage(#PB_Any,File$)   ;Load the specified image from the file with the name File$.
  Width=ImageWidth(image)          ;Determine the width in pixels of image.
  Height=ImageHeight(image)        ;Determine the width in pixels of image.
  If Width>DesktopWidth(#screen) Or Height>DesktopHeight(#screen) ;If the image is larger than the screen.
    Width=DesktopWidth(#screen)    ;The width becomes the width of the selected screen and 
    Height=DesktopHeight(#screen)  ;the height becomes the height of the selected screen.
  EndIf
  OpenWindow(0,0,0,Width/DesktopResolutionX(),Height/DesktopResolutionY(),"ShowPNG",#PB_Window_BorderLess) 
                                   ;Open a window without a frame in the top left-hand corner.
  ImageGadget(0,0,0,Width,Height,ImageID(image));Create an image gadget in the top left-hand corner of the window.
  Repeat
  Until WaitWindowEvent()=#PB_Event_CloseWindow ;Waits until an event occurs. When ALT-F4 is pressed, 
                                                ;end the loop and exit the program.
EndIf 
Documentation ImagePlugin.txt Line 156
Thank you for the suggestion, Jürgen!
But this one looks a bit "overloaded" for a simple example in the command description. Maybe it could become a more extended example (e.g. with proportional image resize) for the PureBasic Examples drawer. Or it should be a lot shorter for the UsePNGImageDecoder() docs...
Bye,
...André
(PureBasicTeam::Docs & Support - PureArea.net | Order:: PureBasic | PureVisionXP)
AZJIO
Addict
Addict
Posts: 2141
Joined: Sun May 14, 2017 1:48 am

Re: Examples for Documentation

Post by AZJIO »

FinishDirectory
Another example of searching for files without recursion.

Code: Select all

Procedure FileSearch(List Files.s(), dir.s, mask.s = "", depth = 130)
	Protected Name.s, c
	Protected Dim hDir(depth)
	Protected Dim SearchPath.s(depth)

	If Right(dir, 1) <> #PS$
		dir + #PS$
	EndIf

	SearchPath(c) = dir
	hDir(c) = ExamineDirectory(#PB_Any, dir, "")
	If Not hDir(c)
		ProcedureReturn
	EndIf

	Repeat
		While NextDirectoryEntry(hDir(c))
			Name = DirectoryEntryName(hDir(c))
			If Name = "." Or Name = ".."
				Continue
			EndIf
			If DirectoryEntryType(hDir(c)) = #PB_DirectoryEntry_Directory
				If c >= depth
					Continue
				EndIf
				dir = SearchPath(c)
				c + 1
				SearchPath(c) = dir + Name + #PS$
				hDir(c) = ExamineDirectory(#PB_Any, SearchPath(c), "")
				If Not hDir(c)
					c - 1
				EndIf
			Else
				If (Not Asc(mask) Or GetExtensionPart(Name) = mask) And AddElement(Files())
					Files() = SearchPath(c) + Name
				EndIf
			EndIf
		Wend
		FinishDirectory(hDir(c))
		c - 1
	Until c < 0
EndProcedure

Define NewList Files.s()
FileSearch(Files(), GetTemporaryDirectory(), "", 130)
ForEach Files()
	Debug Files()
Next
AddElement/NewList (link)

Code: Select all

Define NewList MyList.s()
AddElement(MyList())
MyList() = "WORD"

; get a pointer to the string of a list element, in functions where a pointer to the string is required
If CompareMemoryString(PeekI(@MyList()), @"Word", #PB_String_NoCase) = #PB_String_Equal
	Debug 1
Else
	Debug 0
EndIf

Define *ptr.string
*ptr = @MyList() ; get pointer and access to string without copying data
Debug *ptr\s
Last edited by AZJIO on Sat May 10, 2025 5:50 pm, edited 1 time in total.
AZJIO
Addict
Addict
Posts: 2141
Joined: Sun May 14, 2017 1:48 am

Re: Examples for Documentation

Post by AZJIO »

UnescapeString() - A popular example using the line break character. Useful in ini file.

Code: Select all

Debug UnescapeString("Str1\nStr2") ; inserts a character to replace a special character
There are no escaped characters here

Code: Select all

Debug ~"Test=\"Hello\"."
Debug UnescapeString(~"Test=\"Hello\".")
EscapeString()

Code: Select all

Debug EscapeString("Str1"+ #CRLF$ +"Str2"+ #TAB$ +"3") 
GetMenuItemText()
Here is an example of accessing menu items, the number of which is unknown in advance, for example, the path to a file is specified in the ini file and you can get the path directly from its name.

Code: Select all

#Window = 0
#Menu = 0
Enumeration
	#mNew
	#mOpen
	#mLast
EndEnumeration
Define em, i

If OpenWindow(#Window, 200, 200, 300, 100, "GetMenuItemText Example")
	If CreateMenu(#Menu, WindowID(0))
		MenuTitle("File")
		MenuItem(#mNew, "New")
		MenuItem(#mOpen, "Open")
		For i = #mLast To 10
			MenuItem(i, "Item" + Str(i))
		Next
	EndIf

	Repeat
		Select WaitWindowEvent()
			Case #PB_Event_Menu
				em = EventMenu()
				Select em
					Case #mNew
						Debug "pressed: " + GetMenuItemText(#Menu, #mNew)
					Case #mOpen
						Debug "pressed: " + GetMenuItemText(#Menu, #mOpen)
					Case #mLast To 10
						Debug "pressed: " + GetMenuItemText(#Menu, em)
				EndSelect
			Case #PB_Event_CloseWindow
				Break
		EndSelect
	ForEver
EndIf
HideMenu()
In the description of MenuHeight() you can make a link to this example

Code: Select all

Define Toggle
If OpenWindow(0, 200, 200, 300, 100, "Example HideMenu")
	ButtonGadget(0, 70, 10, 150, 30, "Hide/Show menu")
	If CreateMenu(0, WindowID(0))
		MenuTitle("Project")
		MenuItem(1, "New")
		MenuItem(2, "Open")
	EndIf

	Repeat
		Select WaitWindowEvent()
			Case #PB_Event_Gadget
				Select EventGadget()
					Case 0
						Toggle = Bool(Not Toggle)
						HideMenu(0, Toggle)
						If Toggle
							ResizeGadget(0, #PB_Ignore, 10 + MenuHeight(), #PB_Ignore, #PB_Ignore)
						Else
							ResizeGadget(0, #PB_Ignore, 10, #PB_Ignore, #PB_Ignore)
						EndIf
				EndSelect
			Case #PB_Event_CloseWindow
				Break
		EndSelect
	ForEver
EndIf
AZJIO
Addict
Addict
Posts: 2141
Joined: Sun May 14, 2017 1:48 am

Re: Examples for Documentation

Post by AZJIO »

GetPathPart

Code: Select all

Debug GetPathPart(ProgramFilename())
PlaySound
Sometimes you need to play back the alarm signal. It would be useful to use this example to show how to play the signal 1 time

Code: Select all

EnableExplicit
Define SoundFile.s = "C:\Windows\Media\Alarm01.wav"
Define Length
#RingTone = 0
If FileSize(SoundFile) > 0 And InitSound()
	If LoadSound(#RingTone, SoundFile)
		Length = SoundLength(#RingTone, #PB_Sound_Millisecond)
	EndIf
EndIf

Procedure Sound(*Length.Integer)
	If *Length\i
		PlaySound(#RingTone)
		Delay(*Length\i)
	EndIf
EndProcedure

If OpenWindow(0, 0, 0, 120, 100, "Sound", #PB_Window_SystemMenu | #PB_Window_ScreenCentered)
	CreateThread(@Sound(), @Length)
	Repeat : Until WaitWindowEvent() = #PB_Event_CloseWindow
EndIf
User avatar
Andre
PureBasic Team
PureBasic Team
Posts: 2137
Joined: Fri Apr 25, 2003 6:14 pm
Location: Germany (Saxony, Deutscheinsiedel)
Contact:

Re: Examples for Documentation

Post by Andre »

AZJIO wrote: Sat Mar 01, 2025 8:11 am GetPathPart

Code: Select all

Debug GetPathPart(ProgramFilename())
This one added. For now...
Bye,
...André
(PureBasicTeam::Docs & Support - PureArea.net | Order:: PureBasic | PureVisionXP)
Post Reply