Jump to content
Sign in to follow this  
Sirgijoe

array from .ini file issues

Recommended Posts

Sirgijoe

trying to get a very basic gui that has 2 simple buttons, one is a help button that basically describes how to add a key to the array in the ini file, the other is a button that generates text from the array to a msgbox in random order. for some reason, if anyone knows what I did to screw this up, or what I left out, I would appreciate it, been looking at help topics for awile now and they are all getting blurry. lol

my ini file looks like this

[Topics]

Key = Random 1
Key = Random 2
key = Random 3
key = Random 4
key = Random 5

here is my code

#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#Region ### START Koda GUI section ### Form=
$Form1 = GUICreate("topic generator", 398, 230, 192, 124)
$Pic1 = GUICtrlCreatePic(@ScriptDir & "\bg.jpg", 0, 0, 396, 228)
$Safety = GUICtrlCreateButton("Click me!", 120, 88, 155, 57)
GUICtrlSetBkColor(-1, 0xFFFF00)
$Help = GUICtrlCreateButton("click me for Help", 152, 192, 91, 25)
GUISetState(@SW_SHOW)
Local $var = IniRead(@ScriptDir & "\Safety.ini", "Topics", "key", "NotFound")
$var = IniReadSection("Safety.ini", "Topics")

#EndRegion ### END Koda GUI section ###

$str = ""
For $i = 1 To $var[0][0]
$str &= $var[$i][1] & "|"
Next
$str = StringTrimRight($str, 1)

While 1

$nMsg = GUIGetMsg()
Switch $nMsg

Case $Safety
Safety()

Case $Help
Help()

Case $GUI_EVENT_CLOSE
Exit

EndSwitch
WEnd

Func Safety()
MsgBox(4096, "Result", $var)
GUICtrlSetData(-1, $str)
EndFunc

Func Help()
MsgBox(4096, "Help", "Simply press the safety button for a random daily safety topic. The Safety topics are loaded from the Safety.ini that was distributed with this program. You can add more safety topics by editing a few simple lines of code while also adding your safety topic to the array found in the Safety.ini file! Talk to me if you have any further qeustions.")
EndFunc

thank you in advance

Edited by Sirgijoe

The only dumb question is the one not asked!

Share this post


Link to post
Share on other sites
kylomas

sirgijoe,

INI files are meant to be used like an associative array or dictionary object, meaning that all keys should be unique. Unique keys are required if you are going to use the INI* functions to manage your ini file (otherwise duplicate keys will be overwritten).

However, it is possible to construct an ini file using the FILE* functions and use Inireadsection to read a section of the file.

The following code illustrates these points

; *** Start added by AutoIt3Wrapper ***
#include <Constants.au3>
; *** End added by AutoIt3Wrapper ***
;
#include <array.au3>
;

#AutoIt3Wrapper_Add_Constants=n

;=======================================================================================
;  Example #1 - create ini file using iniwrite and overwrite key #1
;=======================================================================================

local $ini_file_name1   =   @scriptdir & '\initest1.ini', $ret, $aINI

; create an ini file with 10 entries, keys = 1 through 10 and values = A through J

for $1 = 1 to 10
    $ret = iniwrite($ini_file_name1,'Topics',$1,chr(64+$1))
    if $ret = 0 then
        msgbox($mb_ok,'INI WRITE Failed','INI File = ' & $ini_file_name1)
        Exit
    EndIf
Next

; Read the ini file to an array and display it

$aINI = inireadsection($ini_file_name1,'Topics')
_arraydisplay($aINI,'INI Read before key=1 write')

; Write key = 1 to ini file

$ret = iniwrite($ini_file_name1,'Topics','1','what?')
ConsoleWrite($ret & @LF)

; Read the ini file to an array and display it

$aINI = inireadsection($ini_file_name1,'Topics')
_arraydisplay($aINI,'INI Read after key=1 write')

;=======================================================================================
;  Example #2 - create ini file using filewrite and read section
;=======================================================================================

local $ini_file_name2   =   @scriptdir & '\initest2.ini', $ret, $aINI

; create an ini file with 10 entries, keys = 1 through 10 and values = A through J

filedelete($ini_file_name2)
filewriteline($ini_file_name2,'[Topics]')
for $1 = 1 to 10
    filewriteline($ini_file_name2,'key=' & $1)
Next

; Read the ini file to an array and display it

$aINI = inireadsection($ini_file_name2,'Topics')
_arraydisplay($aINI,'INI Read INI file, dup keys')

As concerns your code, the first posted code below shows corrections to get your code to run. Changed, additions are commented. I did this so that you could see what you did wrong.

The second posted code shows what I think you are trying to do, that is, display random entries from an INI file.

#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

#region ### START Koda GUI section ### Form=
$Form1 = GUICreate("topic generator", 398, 230, 192, 124)
$Pic1 = GUICtrlCreatePic(@ScriptDir & "\bg.jpg", 0, 0, 396, 228)
$tip = guictrlcreatelabel('',10,10,378,50,bitor($ss_sunken,$ss_center))         ; added this control to use instead of msgbox
        GUICtrlSetFont($tip,14,800,default,'Comic Sans Serif')                  ; change size, weight and font of $tip label control
$Safety = GUICtrlCreateButton("Click me!", 120, 88, 155, 57)
GUICtrlSetBkColor(-1, 0xFFFF00)
$Help = GUICtrlCreateButton("click me for Help", 152, 192, 91, 25)
GUISetState(@SW_SHOW)

Local $var = IniRead(@ScriptDir & "\Safety.ini", "Topics", "key", "NotFound")   ; this will always return the first key matched (e.g. "random 1")...
                                                                                ; you also overwrite this var with the next instruction
$var = IniReadSection("Safety.ini", "Topics")
#endregion ### END Koda GUI section ###

$str = ""
For $i = 1 To $var[0][0]
    $str &= $var[$i][1] & "|"
Next
$str = StringTrimRight($str, 1)

While 1

    $nMsg = GUIGetMsg()
    Switch $nMsg

        Case $Safety
            Safety()

        Case $Help
            Help()

        Case $GUI_EVENT_CLOSE
            Exit

    EndSwitch
WEnd

Func Safety()
    ;MsgBox(4096, "Result", $var)       ; $var is an array and cannot be reference in this way.  Earlier in the code you construct $str from this array
    ;MsgBox(4096, "Result", $str)       ; using label control instead
    ;GUICtrlSetData(-1, $str)           ; this is referencing the last control created, $help, obviously not what you expect
    GUICtrlSetData($tip, $str)          ; write your ini file to a label control
EndFunc   ;==>Safety

Func Help()
    MsgBox(4096, "Help", "Simply press the safety button for a random daily safety topic. The Safety topics are loaded from the Safety.ini that was distributed with this program. You can add more safety topics by editing a few simple lines of code while also adding your safety topic to the array found in the Safety.ini file! Talk to me (Joe Learn) if you have any further qeustions.")
EndFunc   ;==>Help

This is the code as I think you intended it:

#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>

#region ### START Koda GUI section ### Form=
$Form1 = GUICreate("topic generator", 398, 230, 192, 124)
$Pic1 = GUICtrlCreatePic(@ScriptDir & "\bg.jpg", 0, 0, 396, 228)
$tip = guictrlcreatelabel('',10,10,378,50,bitor($ss_sunken,$ss_center))         ; added this control to use instead of msgbox
        GUICtrlSetFont($tip,14,800,default,'Comic Sans Serif')                  ; change size, weight and font of $tip label control
$Safety = GUICtrlCreateButton("Click me!", 120, 88, 155, 57)
GUICtrlSetBkColor(-1, 0xFFFF00)
$Help = GUICtrlCreateButton("click me for Help", 152, 192, 91, 25)
GUISetState(@SW_SHOW)

$var = IniReadSection("Safety.ini", "Topics")
#endregion ### END Koda GUI section ###

While 1

    $nMsg = GUIGetMsg()
    Switch $nMsg

        Case $Safety
            Safety()

        Case $Help
            Help()

        Case $GUI_EVENT_CLOSE
            Exit

    EndSwitch
WEnd

Func Safety()
    GUICtrlSetData($tip,$var[random(1,ubound($var)-1,1)][1] )   ; randomly selects one of the elements from the array created from the ini file
EndFunc   ;==>Safety

Func Help()
    MsgBox(4096, "Help", "Simply press the safety button for a random daily safety topic. The Safety topics are loaded from the Safety.ini that was distributed with this program. You can add more safety topics by editing a few simple lines of code while also adding your safety topic to the array found in the Safety.ini file! Talk to me (Joe Learn) if you have any further qeustions.")
EndFunc   ;==>Help

Good Luck,

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites
Sirgijoe

thank you so much, I really do appreciate the time you took to help me understand as I am learning!

Also wanted to add that I also found that by having a .jpg image inside my gui, it was making my buttons not function. Perhaps a .bmp image would be better. by commenting out the image line your code works awesome!

Edited by Sirgijoe

The only dumb question is the one not asked!

Share this post


Link to post
Share on other sites
guinness

By the way, I did create _IniReadFile


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

Share this post


Link to post
Share on other sites
kylomas

Sirgijoe,

Any pictures or images in the code was residual from your original post which I left in tact as much as possible so that you could see where you went wrong...

Glad it works,

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites
kylomas

guinness,

By the way, I did create _IniReadFile

Thanks, did'nt know that this snippet existed...

kylomas


Forum Rules         Procedure for posting code

"I like pigs.  Dogs look up to us.  Cats look down on us.  Pigs treat us as equals."

- Sir Winston Churchill

Share this post


Link to post
Share on other sites
Sirgijoe

thanks again to you both


The only dumb question is the one not asked!

Share this post


Link to post
Share on other sites
guinness

You're welcome.


UDF List:

 
_AdapterConnections()_AlwaysRun()_AppMon()_AppMonEx()_ArrayFilter/_ArrayReduce_BinaryBin()_CheckMsgBox()_CmdLineRaw()_ContextMenu()_ConvertLHWebColor()/_ConvertSHWebColor()_DesktopDimensions()_DisplayPassword()_DotNet_Load()/_DotNet_Unload()_Fibonacci()_FileCompare()_FileCompareContents()_FileNameByHandle()_FilePrefix/SRE()_FindInFile()_GetBackgroundColor()/_SetBackgroundColor()_GetConrolID()_GetCtrlClass()_GetDirectoryFormat()_GetDriveMediaType()_GetFilename()/_GetFilenameExt()_GetHardwareID()_GetIP()_GetIP_Country()_GetOSLanguage()_GetSavedSource()_GetStringSize()_GetSystemPaths()_GetURLImage()_GIFImage()_GoogleWeather()_GUICtrlCreateGroup()_GUICtrlListBox_CreateArray()_GUICtrlListView_CreateArray()_GUICtrlListView_SaveCSV()_GUICtrlListView_SaveHTML()_GUICtrlListView_SaveTxt()_GUICtrlListView_SaveXML()_GUICtrlMenu_Recent()_GUICtrlMenu_SetItemImage()_GUICtrlTreeView_CreateArray()_GUIDisable()_GUIImageList_SetIconFromHandle()_GUIRegisterMsg()_GUISetIcon()_Icon_Clear()/_Icon_Set()_IdleTime()_InetGet()_InetGetGUI()_InetGetProgress()_IPDetails()_IsFileOlder()_IsGUID()_IsHex()_IsPalindrome()_IsRegKey()_IsStringRegExp()_IsSystemDrive()_IsUPX()_IsValidType()_IsWebColor()_Language()_Log()_MicrosoftInternetConnectivity()_MSDNDataType()_PathFull/GetRelative/Split()_PathSplitEx()_PrintFromArray()_ProgressSetMarquee()_ReDim()_RockPaperScissors()/_RockPaperScissorsLizardSpock()_ScrollingCredits_SelfDelete()_SelfRename()_SelfUpdate()_SendTo()_ShellAll()_ShellFile()_ShellFolder()_SingletonHWID()_SingletonPID()_Startup()_StringCompact()_StringIsValid()_StringRegExpMetaCharacters()_StringReplaceWholeWord()_StringStripChars()_Temperature()_TrialPeriod()_UKToUSDate()/_USToUKDate()_WinAPI_Create_CTL_CODE()_WinAPI_CreateGUID()_WMIDateStringToDate()/_DateToWMIDateString()Au3 script parsingAutoIt SearchAutoIt3 PortableAutoIt3WrapperToPragmaAutoItWinGetTitle()/AutoItWinSetTitle()CodingDirToHTML5FileInstallrFileReadLastChars()GeoIP databaseGUI - Only Close ButtonGUI ExamplesGUICtrlDeleteImage()GUICtrlGetBkColor()GUICtrlGetStyle()GUIEventsGUIGetBkColor()Int_Parse() & Int_TryParse()IsISBN()LockFile()Mapping CtrlIDsOOP in AutoItParseHeadersToSciTE()PasswordValidPasteBinPosts Per DayPreExpandProtect GlobalsQueue()Resource UpdateResourcesExSciTE JumpSettings INISHELLHOOKShunting-YardSignature CreatorStack()Stopwatch()StringAddLF()/StringStripLF()StringEOLToCRLF()VSCROLLWM_COPYDATAMore Examples...

Updated: 22/04/2018

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
Sign in to follow this  

×