Jump to content

Run more that one instance


Rex
 Share

Recommended Posts

I wrote a small count down program some time ago Count Down Days, and shortly after I started using it I found out the I wanted more that one instance of it.

So I did some brute force copy ini files, that allowed me to start the program with cmdline - it works and I can have x copy's running, but I would like to just run the program once, and then create multiply countdown GUI's, but the my brain just stopped working, and even I did try to bang my head into the wall, and onto the table it still just would start working again.

And now I just have a damn headache 😖

I have rewritten the CDD to use SQLite, and that works swell - it's only that darn multi instance I can't get my brain to figure out a way to do, for me one usage it's not a problem, I can just add to the database, and run CDD with cmd 1.
But I would like the program to be user friendly, so the user can add another instance in the settings, and or start a new instance from the menu.

My idea was some thing like starting the main GUI in a for to loop, but I couldn't figure out how to handle the countdown and extra instances part.

And that is where I hope that some one could point kick me in the right direction, I have spend the last 3 days looking at the monitor and got nowhere, I know the solution is right there with in my reach, my arms is just to short :(

My code so far: (uses cmdline to handle multiply instances), and multiply language is still not implemented.

#NoTrayIcon
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=CDD.ico
#AutoIt3Wrapper_Outfile=CDD.exe
#AutoIt3Wrapper_Res_Fileversion=0.0.0.0
#AutoIt3Wrapper_Res_HiDpi=Y
#AutoIt3Wrapper_Run_After=""d:\Profil\Rex\ISN AutoIt Studio\Projects\Versions Controler\Versions_Controle.exe" "%in%" "%scriptdir%" "%scriptfile%" "%fileversion%""
#AutoIt3Wrapper_Run_After=""d:\Profil\Rex\ISN AutoIt Studio\Projects\Versions Controler\Versions_Controle.exe" "%out%" "%scriptdir%" "%scriptfile%" "%fileversion%""
#AutoIt3Wrapper_Tidy_Stop_OnError=n
#AutoIt3Wrapper_Run_Au3Stripper=y
#Au3Stripper_Parameters=/tl /sf /sv /rsln /rm
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
; #INDEX# =======================================================================================================================
; Title .........: Countdown_Days.au3
; Script Version : 1.0.0
; AutoIt Version : 3.3.15.1 - Created with ISN AutoIt Studio v. 1.08 and 1.09 Dev
; Description ...: Countdown a specfic number of days
; Author(s) .....: Rex
; Creation date..: 2019/02/03
; ===============================================================================================================================

; #CHANGE LOG# ==================================================================================================================
; Changes .......: See project log
; Date ..........:
; ===============================================================================================================================
#cs Lang msg handling
    ; Get the string to handle (All stings should be read into arrays)
    Local $sString =  IniRead('English.lng', 'Settings', 'Msg_DelDef', '')
    ; Then we split the Title and msg into seperat arrays
    Local $aMsg = StringRegExp($sString, '{Title}(.*){Msg}(.*)', 1)
    ; Title would be 0 and msg 1, we also do a Stringformat to handle \r\n (@CRLF) and last we do a stringreplace to replace the {VAR}
    ; with the war we want it to be replaced with - the stringreplace is only nessary when we habe some var that should be placed inside the
    ; msgbox, else we dont need it.
    MsgBox(0, $aMsg[0], StringFormat(StringReplace($aMsg[1], '{VAR}', $aSel[1])))
#ce Lang msg handling

#pragma compile(Fileversion, 1.0.0.11)
#pragma compile(FileDescription, Countdown to a specific day)
#pragma compile(Comments, "Add The days To count down, And the program will countdown, and throw a message / sound")
#pragma compile(ProductName, CountDownDays)
#pragma compile(ProductVersion, 1.0)
#pragma compile(InternalName, "CDD")
#pragma compile(LegalCopyright, © Johnny Rex)
#pragma compile(OriginalFilename, CDD.exe)
;~ #pragma compile(LegalTrademarks, '"Trademark something, and some text in "quotes" etc...')
#pragma compile(CompanyName, 'Rex-IT')
#include <Date.au3>
#include <ColorConstants.au3>
#include <Array.au3>
#include <ButtonConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <ComboConstants.au3>
#include <DateTimeConstants.au3>
#include <EditConstants.au3>
#include <String.au3>
#include <GuiComboBox.au3>
#include <MsgBoxConstants.au3>
#include <WinAPIDlg.au3>
#include <Sound.au3>
#include <GuiListBox.au3>
#include <WinAPISysWin.au3>
#include <FileConstants.au3>
#include <SQLite.au3>
#include <AutoItConstants.au3>
#include <Misc.au3>
#include <ListViewConstants.au3>
#include <GuiListView.au3>
#include <GuiScrollBars.au3>

Opt("GUIOnEventMode", 1)
Opt('MustDeclareVars', 1)
Opt('GUIResizeMode', $GUI_DOCKALL) ; To prevent ctrls to move when we add a new event
OnAutoItExitRegister('MenuItem_ExitClick') ; To save pos at closedown, if savepos is enabled
Global $g_iSecs, $g_iMins, $g_iHours, $g_iDays, $g_iInstance = 0, $g_sDBFile = @ScriptDir & '\Data.db'
; MsgBox Styles
Global $g_iMBErr = BitOR($MB_SETFOREGROUND, $MB_TOPMOST, $MB_ICONERROR), $g_iMBWarn = BitOR($MB_SETFOREGROUND, $MB_TOPMOST, $MB_ICONWARNING)
Global $g_iMBInfo = BitOR($MB_SETFOREGROUND, $MB_TOPMOST, $MB_ICONINFORMATION), $g_iMBQuest = BitOR($MB_SETFOREGROUND, $MB_TOPMOST, $MB_ICONQUESTION)
; GUI Handle
Global $hAddEvent, $idAddEvent, $hEditEvent, $idEditEvent, $hDeleteEvent, $idDelEvent, $hSettings
Global $idSet_DefEvents, $idSet_EditDef, $idSet_Global, $idSet_Color, $idSet_Instance
ConsoleWrite(@CRLF & 'Singleton = ' & _Singleton(@ScriptName) & @CRLF)
; Start SQLite
_SQLite_Startup()
If @error Then
    MsgBox($g_iMBErr, "SQLite Error", "SQLite3.dll Can't be Loaded!" & _
            @CRLF & 'Is SQLite3 installed on the system?' & @CRLF & 'Or is SQLite3.dll in the root of ' & @ScriptDir & @CRLF & @CRLF & _
            'If not SQLite can be downloaded from https://www.sqlite.org/download.html')
    Exit -1
EndIf
; Check if the database file exists
If Not FileExists(@ScriptDir & '\Data.db') Then
    ; The database don't exist, so we creates one
    ; Tell the user that we create a new database, and allow them to cancel the creation
    If MsgBox(BitOR($g_iMBWarn, $MB_OKCANCEL), 'DataBase', 'No database was found!' & @CRLF & _
            'Create a new DataBase?' & @CRLF & 'If Cancel the program will close!!') = $IDCANCEL Then
        OnAutoItExitUnRegister('MenuItem_ExitClick') ; Remove the on exit to prevent error
        Exit
    EndIf
    CreateDB()
    If @error Then
        MsgBox($g_iMBErr, 'DataBase creation failed', 'An error happend when trying to create the DataBase "Data.db" in ' & @ScriptDir & '\' & _
                @CRLF & @CRLF & 'The program will now close!!')
        OnAutoItExitUnRegister('MenuItem_ExitClick') ; Remove the on exit to prevent error
        Exit
    EndIf
EndIf


; Get settings
; First we check if the CDD was called with commandline parms

If $cmdline[0] = 1 Then
    ; If called by cmd line we suspect that the user wants to run an extra instance of the CDD
    ; Convert the cmdline to INT using Number, course we use INT to handle what instance of CDD thats running
    ; and Number would return 0 on most stings not INT
    $cmdline[1] = Number($cmdline[1])
    If Not $cmdline[1] = 0 Or $cmdline[0] = '' Then
        $g_iInstance = $cmdline[1]
    EndIf
EndIf
; Create Settings enum's, so we don't have to remember there pos in the array
Global Enum $eSet_RowID, $eSet_Inst, $eSet_Max, $eSet_Rem, $eSet_SoundPlay, $eSet_Popup, $eSet_Start, $eSet_Lang, _
        $eSet_SoundFile, $eSet_GuiLeft, $eSet_GuiTop, $eSet_Pin
Global $g_aSettings = DBHandle('GetSet', $g_iInstance)
; Create enum for the colors
Global Enum $eCol_RowID, $eCol_Inst, $eCol_GuiBk, $eCol_DragLbl, $eCol_Name, $eCol_Days0, $eCol_Days1, $eCol_Days2, _
        $eCol_Days3, $eCol_DaysLbl, $eCol_Time0, $eCol_Time1, $eCol_Time2, $eCol_Time3, $eCol_TimeColon, $eCol_EventUp, $eCol_EventUpBk
Global $g_aColors = DBHandle('GetColors', $g_iInstance)

; Check if the gui should start at last saved position
If $g_aSettings[$eSet_Rem] = False Then
    $g_aSettings[$eSet_GuiLeft] = -1 ; Default Screen center
    $g_aSettings[$eSet_GuiTop] = -1 ; Default Screen center
EndIf

; Enum event columns
Global Enum $eEvent_RowID, $eEvent_Inst, $eEvent_Name, $eEvent_Desc, $eEvent_Date, $eEvent_SoundFile, $eEvent_SoundPlay, $eEvent_Pop, $eEvent_Enabled
; Get events
Global $g_aEvents = DBHandle('GetEvents', $g_iInstance)

DBHandle('CloseDB', '') ; We close the database after last call

; Check if we have any Events
If UBound($g_aEvents) = 1 Then
    ; If we don't have any events, we creates the array with 1 and Null, 1 to be used to create an empty gui
    ; Null so we know that there isn't any events
    $g_aEvents[0][0] = 1
    $g_aEvents[0][1] = Null
EndIf

Global $g_idLbl_Days[$g_aSettings[$eSet_Max] + 1], _
        $g_idLbl_Hrs[$g_aSettings[$eSet_Max] + 1], _
        $g_idLbl_Min[$g_aSettings[$eSet_Max] + 1], _
        $g_idLbl_Sec[$g_aSettings[$eSet_Max] + 1], _
        $g_idLbl_Event[$g_aSettings[$eSet_Max] + 1]

Global $g_iSpace = 80
Global $g_iGuiHeight = ($g_iSpace * UBound($g_aEvents) - 1) + 8
#Region ### START Koda GUI section ### Form=D:\Profil\Rex\ISN AutoIt Studio\Projects\Countdown Days\GUI\hCountdownDays.kxf
Global $hCountdownDays = GUICreate("CountDown Days", 136, $g_iGuiHeight, $g_aSettings[$eSet_GuiLeft], _
        $g_aSettings[$eSet_GuiTop], $WS_POPUP, $WS_EX_TOOLWINDOW)
; Gui menu
Global $hCountdownDayscontext = GUICtrlCreateContextMenu()

Global $MenuItem_EventHandling = GUICtrlCreateMenu("Event(s)", $hCountdownDayscontext)
Global $MenuItem_AddEvent = GUICtrlCreateMenuItem("Add", $MenuItem_EventHandling)
GUICtrlSetOnEvent(-1, "MenuItem_AddEventClick")
Global $MenuItem_EditEvent = GUICtrlCreateMenuItem("Edit", $MenuItem_EventHandling)
GUICtrlSetOnEvent(-1, "MenuItem_EditEventClick")
Global $MenuItem_DeleteEvent = GUICtrlCreateMenuItem("Delete", $MenuItem_EventHandling)
GUICtrlSetOnEvent(-1, "MenuItem_DeleteEventClick")
Global $MenuItem_Settings = GUICtrlCreateMenuItem("Settings", $hCountdownDayscontext)
GUICtrlSetOnEvent(-1, "MenuItem_SettingsClick")
Global $MenuItem_Pin = GUICtrlCreateMenuItem("Pin in Place", $hCountdownDayscontext)
GUICtrlSetOnEvent(-1, "MenuItem_PinClick")
Global $MenuItem_Exit = GUICtrlCreateMenuItem("Exit", $hCountdownDayscontext)
GUICtrlSetOnEvent(-1, "MenuItem_ExitClick")
GUISetBkColor($g_aColors[$eCol_GuiBk])
Global $idLbl_Move = GUICtrlCreateLabel('', 1, 1, 134, 12, $SS_CENTER, $GUI_WS_EX_PARENTDRAG)
GUICtrlSetFont(-1, 6, 400, 0, "MS Sans Serif")
GUICtrlSetBkColor(-1, $g_aColors[$eCol_DragLbl])

; Create a label to frame the gui, so it don't look to flat
Global $idFrame = GUICtrlCreateLabel('', 0, 0, 136, $g_iGuiHeight, BitOR($SS_SUNKEN, $WS_DISABLED, $SS_SIMPLE))

If $g_aEvents[0][1] = Null Then
    UpdateGui(False) ; Update Countdown GUI
Else
    UpdateGui(True) ; Update Countdown GUI
EndIf
; check if we needs to tick the pin, and disable the Move label
If $g_aSettings[$eSet_Pin] = True Then
    GUICtrlSetState($MenuItem_Pin, $GUI_CHECKED)
    GUICtrlSetState($idLbl_Move, $GUI_DISABLE)
EndIf
; Check if we should disable the add event MenuItem
If UBound($g_aEvents) - 1 >= $g_aSettings[$eSet_Max] Then GUICtrlSetState($MenuItem_AddEvent, $GUI_DISABLE)
; Show the CDD Gui
GUISetState(@SW_SHOW, $hCountdownDays)
#EndRegion ### END Koda GUI section ###


; Start the countdown.
Countdown()
; Register the adlib to call the countdown function every sec
AdlibRegister("Countdown", 1000)

While 1
    Sleep(900)
WEnd


Func MenuItem_AddEventClick()
    ; Create the GUI
    #Region ### START Koda GUI section ### Form=D:\Profil\Rex\ISN AutoIt Studio\Projects\Countdown Days\GUI\hAddEvent.kxf
    $hAddEvent = GUICreate("Add Event", 206, 407, -1, -1, BitOR($WS_SYSMENU, $WS_POPUP, $WS_CAPTION))
    GUISetOnEvent($GUI_EVENT_CLOSE, "hWnd_Close")
    $idAddEvent = GUICtrlCreateDummy() ; Create a dumme, we use this to calculate the CtrlID of the Controls created after the dummy
    GUICtrlCreateLabel("Default Events:", 8, 8, 77, 17) ; This would be dummy + 1 in ID
    GUICtrlCreateCombo("", 8, 24, 185, 25, $CBS_DROPDOWNLIST)
    GUICtrlSetTip(-1, "Saved default events")
    GUICtrlSetOnEvent(-1, "idCombo_EventsChange")
    GUICtrlCreateLabel("Event Name:", 8, 56, 66, 17)
    GUICtrlCreateInput("", 8, 72, 185, 21)
    GUICtrlSetLimit(-1, 24)
    GUICtrlSetTip(-1, "Name of event." & @CRLF & "This is the text that will be shown at the gui." & @CRLF _
             & "Max length is 24 chars")
    GUICtrlCreateLabel("Event description:", 8, 104, 89, 17)
    GUICtrlCreateEdit("", 8, 120, 185, 89, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL))
    GUICtrlSetTip(-1, "Event description." & @CRLF _
             & "This wil be shown as a tip upon hovering, and also in the popup (if popup is enabled)")

    GUICtrlCreateCheckbox("Choose Event date by calendar", 8, 216, 170, 17)
    GUICtrlSetOnEvent(-1, "idCb_ChoseDateClick")
    GUICtrlCreateLabel("Days to event:", 8, 240, 73, 17)
    GUICtrlCreateInput("", 8, 256, 73, 21, BitOR($ES_CENTER, $ES_NUMBER))
    GUICtrlSetLimit(-1, 3)
    GUICtrlSetTip(-1, "Days to the event")
    GUICtrlCreateLabel("Time of event", 112, 240, 69, 17)
    GUICtrlCreateDate('', 112, 256, 82, 21, BitOR($DTS_UPDOWN, $DTS_TIMEFORMAT))
    GUICtrlSendMsg(-1, $DTM_SETFORMATW, 0, 'HH:mm:ss') ; Set time style
    GUICtrlCreateLabel("Event date:", 8, 240, 59, 17)
    GUICtrlSetState(-1, $GUI_HIDE)
    GUICtrlCreateDate('', 8, 256, 186, 21, 0)
    GUICtrlSendMsg(-1, $DTM_SETFORMATW, 0, 'yyyy/MM/dd HH:mm:ss') ; Set Date and Time style
    GUICtrlSetTip(-1, "The end date of the event")
    GUICtrlSetState(-1, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Diasbled and hidden yy default
    GUICtrlCreateLabel("Sound to play:", 8, 280, 72, 17)
    GUICtrlCreateInput($g_aSettings[$eSet_SoundFile], 8, 296, 160, 21, $ES_READONLY) ; Default sound to play at event end
    GUICtrlSetTip(-1, $g_aSettings[$eSet_SoundFile])
    GUICtrlCreateButton("...", 174, 296, 21, 21)
    GUICtrlSetOnEvent(-1, "idBtn_SoundBrowseClick")
    GUICtrlCreateCheckbox("Play sound", 8, 328, 73, 17)
    CbSetState(-1, $g_aSettings[$eSet_SoundPlay])
    GUICtrlCreateCheckbox("Popup", 88, 328, 49, 17)
    CbSetState(-1, $g_aSettings[$eSet_Popup])
    GUICtrlCreateCheckbox("Save as default event", 8, 352, 124, 17)
    GUICtrlSetTip(-1, "Saves the event as a default event, that later can be choosen from the dropdown")
    GUICtrlCreateButton("&Add event", 8, 376, 75, 21)
    GUICtrlSetTip(-1, "Adds the events and closes the add event gui")
    GUICtrlSetOnEvent(-1, "idBtn_AddEventClick")
    GUICtrlCreateButton("&Close", 120, 376, 75, 21)
    GUICtrlSetOnEvent(-1, "hWnd_Close")
    #EndRegion ### END Koda GUI section ###
    
    ; Add default evnets to dropdown
    Local $aDefEvents = DBHandle('GetDefEvents', $g_iInstance)
    If IsArray($aDefEvents) Then
        For $i = 0 To UBound($aDefEvents) - 1
            ; Add the defaults to the combo and revert the name from hex to string.
            GUICtrlSetData($idAddEvent + 2, $aDefEvents[$i][$eEvent_Name])
        Next
    EndIf
    
    ; Set focus to the Event Name input
    GUICtrlSetState($idAddEvent + 4, $GUI_FOCUS)
    ; Show the gui
    GUISetState(@SW_SHOW, $hAddEvent)
EndFunc   ;==>MenuItem_AddEventClick

Func MenuItem_DeleteEventClick()
    ; Create the GUI
    #Region ### START Koda GUI section ### Form=D:\Profil\Rex\ISN AutoIt Studio\Projects\Countdown Days\GUI\hEditEvent.kxf
    $hDeleteEvent = GUICreate("Delete Event", 355, 214, Default, Default, BitOR($WS_SYSMENU, $WS_POPUP, $WS_CAPTION))
    GUISetOnEvent($GUI_EVENT_CLOSE, "hWnd_Close")
    $idDelEvent = GUICtrlCreateDummy()
    GUICtrlCreateLabel("Choose event to delete:", 8, 8, 122, 16)
    GUICtrlCreateListView("rowid|Event name|End date|Enabled", 8, 24, 338, 150, BitOR($LVS_NOSORTHEADER, $WS_VSCROLL), _
            BitOR($LVS_EX_FLATSB, $WS_EX_CLIENTEDGE, $LVS_EX_FULLROWSELECT))
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 0, 10)
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 1, 130)
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 2, 120)
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 3, 56)
    _GUICtrlListView_HideColumn(-1, 0) ; Hides the rowid colum
    GUICtrlSetTip(-1, "Select event to delete")
    GUICtrlCreateButton("&Delete", 8, 184, 75, 21)
    GUICtrlSetTip(-1, "Deletes selected event")
    GUICtrlSetOnEvent(-1, "idBtn_EventDeleteClick")
    GUICtrlCreateButton("&Close", 272, 184, 75, 21)
    GUICtrlSetTip(-1, "Closes the add event, without saving the event.")
    GUICtrlSetOnEvent(-1, "hWnd_Close")
    #EndRegion ### END Koda GUI section ###

    Local $aEvents = DBHandle('GetAllEvents', $g_iInstance)
    If IsArray($aEvents) Then
        For $i = 1 To UBound($aEvents) - 1
            GUICtrlCreateListViewItem($aEvents[$i][$eEvent_RowID] & '|' & $aEvents[$i][$eEvent_Name] & '|' & _
                    $aEvents[$i][$eEvent_Date] & '|' & $aEvents[$i][$eEvent_Enabled], $idDelEvent + 2)
        Next
    EndIf
    If _GUICtrlListView_GetItemCount($idDelEvent + 2) < 7 Then _GUICtrlListView_SetColumnWidth($idDelEvent + 2, 1, 158)
    GUISetState(@SW_SHOW, $hDeleteEvent)
EndFunc   ;==>MenuItem_DeleteEventClick

Func MenuItem_EditEventClick()
    ; Create GUI
    #Region ### START Koda GUI section ### Form=D:\Profil\Rex\ISN AutoIt Studio\Projects\Countdown Days\GUI\hEditEvent.kxf
    $hEditEvent = GUICreate("Edit Event", 292, 429, -1, -1, BitOR($WS_SYSMENU, $WS_POPUP, $WS_CAPTION))
    GUISetOnEvent($GUI_EVENT_CLOSE, "hWnd_Close")
    $idEditEvent = GUICtrlCreateDummy()
    GUICtrlSetOnEvent(-1, 'EventListView')
    GUICtrlCreateLabel("Choose event to edit:", 8, 8, 110, 17)
    GUICtrlCreateListView("rowid|Name|End date", 8, 24, 276, 94, BitOR($LVS_NOSORTHEADER, $WS_HSCROLL), _
            BitOR($LVS_EX_FLATSB, $WS_EX_CLIENTEDGE, $LVS_EX_FULLROWSELECT))
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 0, 10)
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 1, 140)
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 2, 114)
    GUICtrlSetTip(-1, "Double click to select the event")
    _GUICtrlListView_HideColumn(-1, 0) ; Hides the rowid colum
    GUICtrlCreateLabel("Event Name:", 8, 128, 66, 17)
    GUICtrlCreateInput("", 8, 144, 275, 21)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlSetLimit(-1, 24)
    GUICtrlSetTip(-1, "Name of event. This is the text that will be shown at the gui. Max length is 24 chars")
    GUICtrlCreateLabel("Event description:", 8, 176, 89, 17)
    GUICtrlCreateEdit("", 8, 192, 275, 57, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL))
    GUICtrlSetTip(-1, "Event description. This will be shown as a tip upon hovering, and also in the popup (if popup is enabled)")
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateCheckbox("Choose new event date by calender", 8, 264, 200, 17)
    GUICtrlSetOnEvent(-1, "idCb_ChoseDateClick")
    GUICtrlSetState(-1, BitOR($GUI_DISABLE, $GUI_CHECKED))
    GUICtrlCreateLabel("Days to event:", 8, 288, 73, 17)
    GUICtrlSetState(-1, BitOR($GUI_HIDE, $GUI_DISABLE))
    GUICtrlCreateInput("", 8, 304, 73, 21, BitOR($ES_CENTER, $ES_NUMBER))
    GUICtrlSetState(-1, BitOR($GUI_HIDE, $GUI_DISABLE))
    GUICtrlSetLimit(-1, 3)
    GUICtrlSetTip(-1, "Days to the event, time will be from the time the event is added")
    GUICtrlCreateLabel("Time of event", 112, 288, 69, 17)
    GUICtrlSetState(-1, BitOR($GUI_HIDE, $GUI_DISABLE))
    GUICtrlCreateDate('', 112, 304, 82, 21, BitOR($DTS_UPDOWN, $DTS_TIMEFORMAT))
    GUICtrlSetState(-1, BitOR($GUI_HIDE, $GUI_DISABLE))
    GUICtrlSendMsg(-1, $DTM_SETFORMATW, 0, 'HH:mm:ss')
    GUICtrlSetTip(-1, "Time of the event")
    GUICtrlSetState(-1, BitOR($GUI_HIDE, $GUI_DISABLE))
    GUICtrlCreateLabel("Event date:", 8, 288, 59, 17)
    GUICtrlCreateDate('', 8, 304, 186, 21, 0)
    GUICtrlSendMsg(-1, $DTM_SETFORMATW, 0, 'yyyy/MM/dd HH:mm:ss')
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlSetTip(-1, "Choose the end date of the event")
    GUICtrlCreateLabel("Sound to play:", 8, 328, 72, 17)
    GUICtrlCreateInput("", 8, 344, 250, 21, $ES_READONLY)
    GUICtrlCreateButton("...", 264, 344, 21, 21)
    GUICtrlSetOnEvent(-1, "idBtn_SoundBrowseClick")
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateCheckbox("Play sound", 8, 376, 73, 17)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateCheckbox("Popup", 88, 376, 49, 17)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateCheckbox("Enabled", 144, 376, 60, 17)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlSetTip(-1, "Enables or disables the event, if disabled it don't show in the countdown gui")
    GUICtrlCreateButton("&Update", 8, 400, 75, 21)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlSetTip(-1, "Updates the selected event")
    GUICtrlSetOnEvent(-1, "idBtn_UpdateEventClick")
    GUICtrlCreateButton("&Close", 210, 400, 75, 21)
    GUICtrlSetOnEvent(-1, "hWnd_Close")
    #EndRegion ### END Koda GUI section ###
    ; Add events to the listView
    Local $aEvents = DBHandle('GetAllEvents', $g_iInstance)
    If IsArray($aEvents) Then
        For $i = 1 To UBound($aEvents) - 1
            GUICtrlCreateListViewItem($aEvents[$i][$eEvent_RowID] & '|' & $aEvents[$i][$eEvent_Name] & '|' & $aEvents[$i][$eEvent_Date], _
                    $idEditEvent + 2)
        Next
    EndIf
    If _GUICtrlListView_GetItemCount($idEditEvent + 2) < 3 Then _GUICtrlListView_SetColumnWidth($idEditEvent + 2, 1, 158)
    ; Show the gui
    GUISetState(@SW_SHOW, $hEditEvent)
    ; Catch double click in Edit event listview
    GUIRegisterMsg($WM_NOTIFY, "WM_NOTIFY")
EndFunc   ;==>MenuItem_EditEventClick

Func MenuItem_SettingsClick()
    #Region ### START Koda GUI section ### Form=D:\Profil\Rex\ISN AutoIt Studio\Projects\Countdown Days\GUI\hSettings.kxf
    $hSettings = GUICreate("Settings", 523, 478, Default, Default, BitOR($WS_SYSMENU, $WS_POPUP, $WS_CAPTION))
    GUISetOnEvent($GUI_EVENT_CLOSE, "hWnd_Close")
    
    $idSet_DefEvents = GUICtrlCreateGroup("Default events:", 8, 8, 201, 185)
    GUICtrlCreateListView("RowID|Name", 16, 24, 186, 134, BitOR($GUI_SS_DEFAULT_LISTVIEW, $LVS_NOCOLUMNHEADER, $LVS_NOSORTHEADER), BitOR($WS_EX_CLIENTEDGE, $LVS_EX_FULLROWSELECT))
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 0, 0) ; Hide the RowID colum
    GUICtrlSendMsg(-1, $LVM_SETCOLUMNWIDTH, 1, 170)
    GUICtrlSetTip(-1, "Default events that, can be picked from add event.")
    GUICtrlCreateRadio("Edit", 16, 168, 40, 17)
    GUICtrlSetState(-1, $GUI_CHECKED)
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlSetTip(-1, "Edit selected event")
    GUICtrlCreateRadio("Delete", 64, 168, 60, 17)
    GUICtrlSetTip(-1, "Delete the selected event")
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateButton("Edit", 144, 168, 50, 20)
    GUICtrlSetTip(-1, "Deletes the selected Default event")
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    
    $idSet_Instance = GUICtrlCreateGroup("Instance", 8, 200, 201, 49)
    GUICtrlCreateInput("0", 16, 217, 41, 20, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_READONLY, $ES_NUMBER))
    GUICtrlCreateUpdown(-1)
    GUICtrlSetLimit(-1, 3, 0)
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateRadio("Add", 64, 218, 40, 17)
    GUICtrlSetTip(-1, 'Adds a nother Instance to the database')
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateRadio("Remove", 106, 218, 60, 17)
    GUICtrlSetTip(-1, 'Removes an Instance from the DataBase,' & @CRLF & 'this will also remove all events added inder that Instance')
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateButton("OK", 172, 217, 29, 20)
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateGroup("", -99, -99, 1, 1)
    
    $idSet_Global = GUICtrlCreateGroup("Global settings:", 8, 256, 201, 185)
    GUICtrlCreateLabel("Max number of events:", 16, 272, 112, 21, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, "Max number of events." & @CRLF & "On a 1920x1080 Screen the max would be aprox 13 events.")
    GUICtrlCreateInput($g_aSettings[$eSet_Max], 138, 272, 21, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_CENTER, $ES_NUMBER))
    GUICtrlSetLimit(-1, 2)
    GUICtrlSetTip(-1, "Max number of events." & @CRLF & "On a 1920x1080 Screen the max would be aprox 13 events.")
    GUICtrlCreateCheckbox("Remember position", 16, 296, 110, 17)
    CbSetState(-1, $g_aSettings[$eSet_Rem])
    GUICtrlSetTip(-1, "When countdown is closed" & @CRLF & " it saves the position it was placed, and starts at that position.")
    GUICtrlCreateCheckbox("Play Sound", 128, 296, 74, 17)
    CbSetState(-1, $g_aSettings[$eSet_SoundPlay])
    GUICtrlSetTip(-1, "Plays a sound when the event time is up.")
    GUICtrlCreateCheckbox("Show popup", 16, 320, 80, 17)
    CbSetState(-1, $g_aSettings[$eSet_Popup])
    GUICtrlSetTip(-1, "Shows a popup windows, when the event time is up." & @CRLF & "The content of the popup windows will be the event descrption.")
    GUICtrlCreateCheckbox("Start with system", 104, 320, 98, 17)
    CbSetState(-1, $g_aSettings[$eSet_Start])
    GUICtrlSetTip(-1, "Start the program with windows")
    GUICtrlCreateLabel("Language:", 16, 344, 55, 17)
    GUICtrlCreateCombo($g_aSettings[$eSet_Lang], 16, 360, 185, 21, BitOR($CBS_DROPDOWNLIST, $CBS_AUTOHSCROLL))
    GUICtrlSetTip(-1, 'The language to use for menus, lables, buttons ect.')
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateLabel("Default alarm sound:", 16, 392, 101, 17)
    GUICtrlCreateInput($g_aSettings[$eSet_SoundFile], 16, 408, 161, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_READONLY))
    GUICtrlSetTip(-1, "Default sound to play when the event timeis up." & @CRLF & $g_aSettings[$eSet_SoundFile])
    GUICtrlCreateButton("...", 184, 408, 21, 21)
    GUICtrlSetOnEvent(-1, "idBtn_SoundBrowseClick")
    GUICtrlCreateGroup("", -99, -99, 1, 1)

    $idSet_Color = GUICtrlCreateGroup("Change Colors:", 216, 8, 297, 217)
    GUICtrlCreateLabel("GUI BkGround", 224, 24, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'The background color of the GUI')
    GUICtrlCreateButton("", 336, 24, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_GuiBk])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("GUI Drag label:", 224, 48, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'Color of the drag label')
    GUICtrlCreateButton("", 336, 48, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_DragLbl])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Event name:", 224, 72, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'Color of the Event text')
    GUICtrlCreateButton("", 336, 72, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Name])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Days default:", 224, 96, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When more that 15 days left')
    GUICtrlCreateButton("", 336, 96, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Days0])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Days 5 to 0:", 224, 120, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When between 5 and 0 days left')
    GUICtrlCreateButton("", 336, 120, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Days1])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Days 10 to 6:", 224, 144, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When between 10 and 6 days left')
    GUICtrlCreateButton("", 336, 144, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Days2])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Days 15 to 11:", 224, 168, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When between 15 to 11 days left')
    GUICtrlCreateButton("", 336, 168, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Days3])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Days label:", 224, 192, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'Color of the static label "Days"')
    GUICtrlCreateButton("", 336, 192, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_DaysLbl])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Time default:", 376, 24, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When more than 0 days left')
    GUICtrlCreateButton("", 488, 24, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Time0])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Time 6 to 0:", 376, 48, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When 0 days and between 6 and 0 hours left')
    GUICtrlCreateButton("", 488, 48, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Time1])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Time 12 to 7:", 376, 72, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When 0 days and between 12 to 7 hours left')
    GUICtrlCreateButton("", 488, 72, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Time2])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Time 23 to 13:", 376, 96, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'When 0 days and between 23 and 13 hours left')
    GUICtrlCreateButton("", 488, 96, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_Time3])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Time colon:", 376, 120, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, "The static label ':' between hour, min and sec")
    GUICtrlCreateButton("", 488, 120, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_TimeColon])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Event up:", 376, 144, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'Event name text color when the event time is up')
    GUICtrlCreateButton("", 488, 144, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_EventUp])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateLabel("Event up BkGround:", 376, 168, 110, 20, $SS_CENTERIMAGE)
    GUICtrlSetTip(-1, 'Background color of event name, when time is up')
    GUICtrlCreateButton("", 488, 168, 20, 20)
    GUICtrlSetBkColor(-1, $g_aColors[$eCol_EventUpBk])
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateButton("Default", 432, 192, 75, 20)
    GUICtrlSetTip(-1, "Set the colors to default")
    GUICtrlSetOnEvent(-1, 'Click_Settings')
    GUICtrlCreateGroup("", -99, -99, 1, 1)

    $idSet_EditDef = GUICtrlCreateGroup("Edit default event:", 216, 232, 297, 209)
    GUICtrlCreateLabel("Event name:", 224, 248, 64, 21, $SS_CENTERIMAGE)
    GUICtrlCreateInput("", 288, 248, 137, 21)
    GUICtrlSetLimit(-1, 24)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateLabel("Days:", 432, 248, 31, 20, $SS_CENTERIMAGE)
    GUICtrlCreateInput("", 464, 248, 41, 21)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateLabel("Event description:", 224, 272, 89, 17)
    GUICtrlCreateEdit("", 224, 288, 281, 81, BitOR($ES_AUTOVSCROLL, $ES_WANTRETURN, $WS_VSCROLL))
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateLabel("Alarm sound:", 224, 384, 65, 20, $SS_CENTERIMAGE)
    GUICtrlCreateInput('', 288, 384, 193, 21, BitOR($GUI_SS_DEFAULT_INPUT, $ES_READONLY))
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateButton("...", 488, 384, 21, 21)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlSetOnEvent(-1, "idBtn_SoundBrowseClick")
    GUICtrlCreateCheckbox("Play sound", 224, 412, 72, 17)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateCheckbox("Show popup", 304, 412, 80, 17)
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlCreateLabel("", 464, 416, 10, 17) ; Hidden label to hold the row id of the def event thats been edited
    GUICtrlSetState(-1, $GUI_DISABLE)
    GUICtrlSetState(-1, $GUI_HIDE)
    GUICtrlCreateGroup("", -99, -99, 1, 1)

    GUICtrlCreateButton("OK", 8, 448, 75, 21)
    GUICtrlSetOnEvent(-1, "Click_Settings")
    GUICtrlCreateButton("Close", 440, 448, 75, 21)
    GUICtrlSetOnEvent(-1, "hWnd_Close")
    #EndRegion ### END Koda GUI section ###
    
    
    ; Update the gui with info's from the settings file, or if no settings file exists, with defaults
    ; Add default evnets to Listbox (The events that is saved, and can be loaded in add event)
    Local $aDefEvents = DBHandle('GetDefEvents', '')
    If IsArray($aDefEvents) Then ; If it's an array we continue
        
        For $i = 0 To UBound($aDefEvents) - 1
            
            ; Add the defaults to the listbox and convert the name from hex to string.
            GUICtrlCreateListViewItem($aDefEvents[$i][0] & '|' & $aDefEvents[$i][1], $idSet_DefEvents + 1)
            
        Next
    EndIf

    ; Check if the Remember, playsound, popup and Start with windows is enabled in settings
    CbSetState($idSet_Global + 3, $g_aSettings[$eSet_Rem])
    CbSetState($idSet_Global + 4, $g_aSettings[$eSet_SoundPlay])
    CbSetState($idSet_Global + 5, $g_aSettings[$eSet_Popup])
    CbSetState($idSet_Global + 6, $g_aSettings[$eSet_Start])
    
    ; Show the gui
    GUISetState(@SW_SHOW, $hSettings)
EndFunc   ;==>MenuItem_SettingsClick

Func MenuItem_ExitClick()
    ; We only run this function Once
    Local Static $bRunned = True
    If $bRunned = True Then
        $bRunned = False
        ; Check if the program should save it's poition
        If $g_aSettings[$eSet_Rem] = True Then
            SetPos()
        EndIf
        ; Delete the CDD GUI
        GUIDelete($hCountdownDays)
        ; VACUUM the DataBase
        DBHandle('VACUUM', '')
        ; Close Sql
        _SQLite_Close()
    EndIf
    Exit
EndFunc   ;==>MenuItem_ExitClick
Func SetPos()
    ; get the position of the GUI
    Local $aPos = WinGetPos($hCountdownDays)
    Local $aPos2D[3][2] = [[$g_aSettings[$eSet_RowID], $g_aSettings[$eSet_RowID]], ['PosLeft', $aPos[0]], ['PosTop', $aPos[1]]]
    ; Update the position in the DataBase
    DBHandle('UpdatePos', $aPos2D)
    ; Update the Settings array
    $g_aSettings[$eSet_GuiLeft] = $aPos[0]
    $g_aSettings[$eSet_GuiTop] = $aPos[1]
EndFunc   ;==>SetPos

Func MenuItem_PinClick()
    ; Get state of MenuItem Pin in place
    ; If the pin is enabled, the gui can't be moved
    ; When pinned Save last pos is automaticly enabled
    If BitAND(GUICtrlRead($MenuItem_Pin), $GUI_CHECKED) = $GUI_CHECKED Then
        GUICtrlSetState($MenuItem_Pin, $GUI_UNCHECKED)
        $g_aSettings[$eSet_Pin] = False ; Update the var
        DBHandle('UpdateSingleSet', 'Pin|False')
        GUICtrlSetState($idLbl_Move, $GUI_ENABLE) ; Enable the label, this allows the gui to be moved
    Else
        GUICtrlSetState($MenuItem_Pin, $GUI_CHECKED)
        $g_aSettings[$eSet_Pin] = True ; Update the var
        $g_aSettings[$eSet_Rem] = True ; Enables remember last pos
        DBHandle('UpdateSingleSet', 'Pin|True')
        DBHandle('UpdateSingleSet', 'Remember|True')
        SetPos()
        DBHandle('CloseDB', '')
        GUICtrlSetState($idLbl_Move, $GUI_DISABLE) ; Disable the label, preventing the gui to be moved
    EndIf
    
EndFunc   ;==>MenuItem_PinClick

Func hWnd_Close()
    ; Delete the gui
    GUIDelete(@GUI_WinHandle)
    ; Close the database
    DBHandle('CloseDb', '')
EndFunc   ;==>hWnd_Close
Func Click_Main()
    ; only one thing calls this function, and that a event label
    ; And all we chould do here is to kil the playing sound
    ; Create a static to prevent further clicks (due to bug in setonevent remove)
    Local Static $iCtrlID = 0
    
    If $iCtrlID <> @GUI_CtrlId Then
        ConsoleWrite(@CRLF & 'Label Click = ' & @GUI_CtrlId & @CRLF)
        $iCtrlID = @GUI_CtrlId
        SoundPlay('')
        GUICtrlSetOnEvent(@GUI_CtrlId, '') ; And this don't work due to a bug in autoit :'(
    EndIf
EndFunc   ;==>Click_Main
Func Click_Settings()
    ; Handle Button, Checkbox, Radios etc. clicks
    ; First we get the Winhandle of the win in where the click came from
    ConsoleWrite(@CRLF & 'Id = ' & @GUI_CtrlId & @CRLF)
    Switch @GUI_CtrlId
        Case $idSet_DefEvents + 2 ; Default events radio Edit
            ; Set butten text Edit
            GUICtrlSetData($idSet_DefEvents + 4, 'Edit')
        Case $idSet_DefEvents + 3 ; Default events Radio delete
            ; Set button text Delete
            GUICtrlSetData($idSet_DefEvents + 4, 'Delete')
        Case $idSet_DefEvents + 4 ; Default evnets Button Edit/Remove
            ; Check that an event has been chosen
            If GUICtrlRead($idSet_DefEvents + 1) Then
                ; Read the selected event, and split the read info where row 0 would be the rowid, and row 1 the Name of the event
                Local $aSel = StringSplit(StringTrimRight(GUICtrlRead(GUICtrlRead($idSet_DefEvents + 1)), 1), '|', $STR_NOCOUNT)
                
                ; Check if we should Delete or edit the selected event
                Switch GUICtrlRead($idSet_DefEvents + 4)
                    Case 'Edit'
                        
                        Local $aData = DBHandle('GetSingleDefEvent', $aSel[0])
                        
                        ; Update the edit event ctrls
                        GUICtrlSetData($idSet_EditDef + 2, $aData[0]) ; Event Name
                        GUICtrlSetData($idSet_EditDef + 4, $aData[2]) ; Days
                        GUICtrlSetData($idSet_EditDef + 6, $aData[1]) ; Description
                        GUICtrlSetData($idSet_EditDef + 8, $aData[3]) ; Sound file
                        CbSetState($idSet_EditDef + 10, StringToType($aData[4])) ; Play Sound
                        CbSetState($idSet_EditDef + 11, StringToType($aData[5])) ; Show popup
                        ; Set rowid of the event we just edited, to the hidden label - So we can update it later wehen/if the ok button is hit
                        GUICtrlSetData($idSet_EditDef + 12, $aSel[0]) ; Hidden label to hold rowid of the edited event
                        
                        ; And enable the controls.
                        For $i = 2 To 11
                            GUICtrlSetState($idSet_EditDef + $i, $GUI_ENABLE)
                        Next
                    Case 'Delete'
                        ; If the user clicks Delete
                        ; First we warn, that the selected will be deletede, and can't be restored
                        Local $iStyle = BitOR($MB_ICONWARNING, $MB_SETFOREGROUND, $MB_TOPMOST, $MB_SYSTEMMODAL, $MB_YESNO)
                        If MsgBox($iStyle, 'Delete default event', 'The default event: ' & $aSel[1] & @CRLF & "Will be delete, and can't be restored!" & _
                                @CRLF & @CRLF & 'Do you want to continue?') = $IDNO Then Return
                        ; If msg = yes then remove the item from the database and listview
                        DBHandle('DelSingleDefEvent', $aSel[0])
                        DBHandle('CloseDB', '')
                        _GUICtrlListView_DeleteItemsSelected($idSet_DefEvents + 1)
                EndSwitch
            EndIf
        Case $idSet_Instance + 2 ; Instance Updown
            ConsoleWrite(@CRLF & 'Read text from ctrlid 2 = ' & GUICtrlRead(@GUI_CtrlId - 1) & @CRLF)
        Case $idSet_Instance + 3 ; Instance Radio Add
            ConsoleWrite(@CRLF & 'Read text from ctrlid 3= ' & GUICtrlGetState(@GUI_CtrlId) & @CRLF)
        Case $idSet_Instance + 4 ; Instance Radio Delete
            ConsoleWrite(@CRLF & 'Read text from ctrlid 4= ' & GUICtrlGetState(@GUI_CtrlId) & @CRLF)
        Case $idSet_Instance + 5 ; Instance button OK
            ConsoleWrite(@CRLF & 'Read text from ctrlid 5= ' & GUICtrlRead(@GUI_CtrlId) & @CRLF)
        Case $idSet_Color + 2 To $idSet_Color + 30 ; Colors Colorpicker buttons
            Local $dColor = _ChooseColor(2, 0, 0, @GUI_WinHandle)
            If Not @error Then
                ; Set the background color of the button, to show the user what color was choosen
                GUICtrlSetBkColor(@GUI_CtrlId, $dColor)
                ; Set text color to same as background, so we can hide the text we add
                GUICtrlSetColor(@GUI_CtrlId, $dColor)
                ; Set the text size to 1, so the button don't look funny when we add text to it
                GUICtrlSetFont(@GUI_CtrlId, 1)
                ; Write the colorcode as text on the button, we do this so when we saves the settings
                ; we can read the color code from the button
                GUICtrlSetData(@GUI_CtrlId, $dColor)
            EndIf
        Case $idSet_Color + 31 ; Colors Button Default
            ; Set default colors
            Local $aCol = StringSplit('0x4E4E4E|0x808080|0xFFFFFF|0x000000|0xFF0000|0xFFFF00|0x008000|0x000000|0x000000|' & _
                    '0xFF0000|0xFFFF00|0x008000|0x000000|0xFF0000|0xFFFF00', '|', $STR_NOCOUNT)
            Local $y = 0
            For $i = 2 To 30 Step 2
                ; Set the background color of the button, to show the user what color was choosen
                GUICtrlSetBkColor($idSet_Color + $i, $aCol[$y])
                ; Set text color to same as background, so we can hide the text we add
                GUICtrlSetColor($idSet_Color + $i, $aCol[$y])
                ; Set the text size to 1, so the button don't look funny when we add text to it
                GUICtrlSetFont($idSet_Color + $i, 1)
                ; Write the colorcode as text on the button, we do this so when we saves the settings
                ; we can read the color code from the button
                GUICtrlSetData($idSet_Color + $i, $aCol[$y])
                $y += 1
            Next
        Case $idSet_EditDef + 14 ; Settings OK button
            ; Read infos and update the settings.
            ; Get maxEvents
            Local $iMax = GUICtrlRead($idSet_Global + 2)
            If $iMax = '' Then
                MsgBox(BitOR($MB_ICONERROR, $MB_SETFOREGROUND, $MB_TOPMOST), 'Max number of events', _
                        "The input Max number of events is empty, but it shouldn't be" & @CRLF & 'Please type number of max allowed events!!')
                GUICtrlSetState($idSet_Global + 2, $GUI_FOCUS)
                Return
            EndIf
            
            ; Get Colors
            Local $y = 0
            For $i = 2 To 30 Step 2
                ; Read the selected color by reading the button text
                Local $dBtnColor = GUICtrlRead($idSet_Color + $i)
                ; Check if the button has any text, if so we update the color array with the new color
                If $dBtnColor <> '' Then $g_aColors[$y] = $dBtnColor
                $y += 1
            Next
            
            ; Update Settings Array
            ; Rember last position
            $g_aSettings[$eSet_Rem] = (GUICtrlRead($idSet_Global + 3) = $GUI_CHECKED) ? True : False
            ; Play sound
            $g_aSettings[$eSet_SoundPlay] = (GUICtrlRead($idSet_Global + 4) = $GUI_CHECKED) ? True : False
            ; Show popup
            $g_aSettings[$eSet_Popup] = (GUICtrlRead($idSet_Global + 5) = $GUI_CHECKED) ? True : False
            ; Start with windows
            $g_aSettings[$eSet_Start] = (GUICtrlRead($idSet_Global + 6) = $GUI_CHECKED) ? True : False
            ; Sound file
            $g_aSettings[$eSet_SoundFile] = GUICtrlRead($idSet_Global + 10)


            ; Check if the program should rember it's last position
            If GUICtrlRead($idSet_Global + 3) = $GUI_CHECKED Then
                SetPos()
            EndIf
            ; Check if the program should start with windows
            If GUICtrlRead($idSet_Global + 6) = $GUI_CHECKED Then
                RegWrite('HKCU\Software\Microsoft\Windows\CurrentVersion\Run', 'CDD_' & $g_iInstance, 'REG_SZ', @ScriptFullPath & ' ' & $g_iInstance)
            Else
                RegDelete('HKCU\Software\Microsoft\Windows\CurrentVersion\Run', 'CDD_' & $g_iInstance)
            EndIf

            ; Check if an event has been edited
            Local $iRowID = GUICtrlRead($idSet_EditDef + 12)
            If $iRowID <> '' Then
                Local $aDefEvents[7][2]
                $aDefEvents[0][0] = $iRowID
                $aDefEvents[0][1] = ''
                $aDefEvents[1][0] = 'Name'
                $aDefEvents[1][1] = GUICtrlRead($idSet_EditDef + 2)
                $aDefEvents[2][0] = 'Desc'
                $aDefEvents[2][1] = GUICtrlRead($idSet_EditDef + 6)
                $aDefEvents[3][0] = 'Days'
                $aDefEvents[3][1] = GUICtrlRead($idSet_EditDef + 4)
                $aDefEvents[4][0] = 'Soundfile'
                $aDefEvents[4][1] = GUICtrlRead($idSet_EditDef + 8)
                $aDefEvents[5][0] = 'PlaySound'
                $aDefEvents[5][1] = (GUICtrlRead($idSet_EditDef + 10) = $GUI_CHECKED) ? True : False
                $aDefEvents[6][0] = 'PopUp'
                $aDefEvents[6][1] = (GUICtrlRead($idSet_EditDef + 11) = $GUI_CHECKED) ? True : False
                ; Update event in DataBase
                DBHandle('UpdateDefEvent', $aDefEvents)
            EndIf

            ; Set GUI background color
            GUISetBkColor($g_aColors[$eCol_GuiBk], $hCountdownDays)
            ; Set the color of the drag lable
            GUICtrlSetBkColor($idLbl_Move, $g_aColors[$eCol_DragLbl])
            ; Update the gui
            UpdateGui(False)
            ; And finaly update the DataBase
            DBHandle('UpdateSet', '')
            DBHandle('CloseDB', '')
            ; Delete the GUI
            GUIDelete($hSettings)
    EndSwitch
    
EndFunc   ;==>Click_Settings



Func idCb_ChoseDateClick()
    ; Handel the Choose by date checkbox for either Add or Edit event gui
    ; First we check if it's Add or Edit event gui that is asking
    Switch @GUI_WinHandle ; The handle of the current gui
        Case WinGetHandle($hAddEvent) ; If its Add event
            Local $iCtrlID = $idAddEvent
        Case WinGetHandle($hEditEvent) ; If its Edit event
            Local $iCtrlID = $idEditEvent
    EndSwitch
    
    ; Get state of checkbox
    Local $bChoseDate = (GUICtrlRead($iCtrlID + 7) = $GUI_CHECKED) ? True : False
    
    ; Handel state of checkbox
    Switch $bChoseDate
        Case True
            
            ; Hide, disable and clear days and time input / label
            GUICtrlSetState($iCtrlID + 8, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Hide the label Days to event
            GUICtrlSetState($iCtrlID + 9, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Hide the input Days to event
            GUICtrlSetData($iCtrlID + 9, '') ; Clear the input Days to event
            GUICtrlSetState($iCtrlID + 10, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Hides the label Time to event
            GUICtrlSetState($iCtrlID + 11, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Hide the TimePicker Time to event

            ; Show date picker and lable
            GUICtrlSetState($iCtrlID + 12, BitOR($GUI_ENABLE, $GUI_SHOW)) ; Show the label Event date
            GUICtrlSetState($iCtrlID + 13, BitOR($GUI_ENABLE, $GUI_SHOW)) ; Show the Date time picker

        Case False
            
            ; Hide, disable and clear date picker and label
            GUICtrlSetState($iCtrlID + 12, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Hide the label Event date
            GUICtrlSetState($iCtrlID + 13, BitOR($GUI_DISABLE, $GUI_HIDE)) ; Hide the Date time picker

            ; Enable, show and set time input / labels
            GUICtrlSetState($iCtrlID + 8, BitOR($GUI_ENABLE, $GUI_SHOW)) ; Show the label Days to event
            GUICtrlSetState($iCtrlID + 9, BitOR($GUI_ENABLE, $GUI_SHOW)) ; Shows the Input Days to event
            GUICtrlSetState($iCtrlID + 10, BitOR($GUI_ENABLE, $GUI_SHOW)) ; Shows the label Time to event
            GUICtrlSetState($iCtrlID + 11, BitOR($GUI_ENABLE, $GUI_SHOW)) ; Show time picker
            
    EndSwitch
    
EndFunc   ;==>idCb_ChoseDateClick


Func idBtn_AddEventClick()
    ; First we handle the inputs etc.
    ; Read data from gui, and add it to an array
    Local $sReadName = GUICtrlRead($idAddEvent + 4) ; Read name from Event name input
    If $sReadName = '' Then
        MsgBox(BitOR($MB_ICONERROR, $MB_SETFOREGROUND, $MB_TOPMOST), 'Event Name Error', 'The input "Event name" was empty!' & _
                @CRLF & 'Please enter type an Event name!!')
        GUICtrlSetState($idAddEvent + 4, $GUI_FOCUS)
        Return
    EndIf

    ; Handel state of checkbox choose event date by calendar
    Switch (GUICtrlRead($idAddEvent + 7) = $GUI_CHECKED) ? True : False
        Case True
            ; Get DTS from date picker
            Local $sDTS = GUICtrlRead($idAddEvent + 13)
        Case False
            ; Check that days is not empty
            Local $sReadDays = GUICtrlRead($idAddEvent + 9)
            If $sReadDays <> '' Then
                Local $sDTS = CalcEndDate($sReadDays, GUICtrlRead($idAddEvent + 11))
            Else
                MsgBox(BitOR($MB_ICONERROR, $MB_SETFOREGROUND, $MB_TOPMOST), 'Days Error', 'The input "Days to event" was empty!' & _
                        @CRLF & 'Please enter number of days!!')
                GUICtrlSetState($idAddEvent + 9, $GUI_FOCUS)
                Return
            EndIf
    EndSwitch
    Local $sEvent = @YEAR & @MON & @MDAY & @HOUR & @MIN & @SEC ; We use this to prevent events with same SectionNames in the ini file.
    ; Create an array to hold the Event values
    Local $aValues[8]
    $aValues[0] = $g_iInstance
    $aValues[1] = $sReadName ; Event Name
    $aValues[2] = StringReplace(GUICtrlRead($idAddEvent + 6), @CRLF, ' ') ; Get data from edit
    $aValues[3] = StringRegExpReplace($sDTS, "(\d{4})/(\d{2})/(\d{2})(.*)", "$1-$2-$3$4", 0) ; Event end date
    $aValues[4] = GUICtrlRead($idAddEvent + 15) ; Get sound to play from input sound to play
    $aValues[5] = (GUICtrlRead($idAddEvent + 17) = $GUI_CHECKED) ? True : False ; To play or not play sound at event end
    $aValues[6] = (GUICtrlRead($idAddEvent + 18) = $GUI_CHECKED) ? True : False ; To show or not to show popup at event end
    $aValues[7] = 'True' ; The Event is Enabled by default
    DBHandle('AddEvent', $aValues)
    
    ; Get state of save as default checkbox
    If GUICtrlRead($idAddEvent + 19) = $GUI_CHECKED Then
        ; We don't save all the info, only Days to Event, Sound to play, To play o not play the sound and to show or not to show the popup
        ; Trim the array from unneeded data
        _ArrayDelete($aValues, '0;7') ; Remove Instance and Enabled
        
        ; Get the amount of days to event +1 course the cal is only returing whole days and the event will be in x days and 23:59:xx sec
        ; There for we needs to ad +1, so it will correspond to the amount of days th euser might have entered in Days to Event
        $aValues[2] = _DateDiff('D', _NowCalc(), $sDTS) + 1
        DBHandle('AddDefEvent', $aValues)
;~      IniWriteSection($g_sSetFile, _StringToHex(GUICtrlRead($idAddEvent + 4)), $aValues) ; Write the info to Settings file
    EndIf
    hWnd_Close() ; Close the gui
    
    If $g_aEvents[0][1] = Null Then
        UpdateGui(True) ; Update Countdown GUI with Msg
    Else
        UpdateGui(False) ; Update Countdown GUI without msg
    EndIf

EndFunc   ;==>idBtn_AddEventClick

Func idBtn_UpdateEventClick()
    
    ; First we handle the inputs etc.
    ; Read data from gui, and add it to an array
    Local $sReadName = GUICtrlRead($idEditEvent + 4) ; Read name from Event name input
    If $sReadName = '' Then
        MsgBox(BitOR($MB_ICONERROR, $MB_SETFOREGROUND, $MB_TOPMOST), 'Event Name Error', 'The input "Event name" was empty!' & _
                @CRLF & 'Please enter type an Event name!!')
        GUICtrlSetState($idEditEvent + 4, $GUI_FOCUS)
        Return
    EndIf

    ; Handel state of checkbox
    Switch (GUICtrlRead($idEditEvent + 7) = $GUI_CHECKED) ? True : False
        Case True
            ; Get DTS from date picker
            Local $sDTS = GUICtrlRead($idEditEvent + 13)
        Case False
            ; Check that days is not empty
            Local $sReadDays = GUICtrlRead($idEditEvent + 9)
            If $sReadDays <> '' Then
                Local $sDTS = CalcEndDate($sReadDays, GUICtrlRead($idEditEvent + 11))
            Else
                MsgBox(BitOR($MB_ICONERROR, $MB_SETFOREGROUND, $MB_TOPMOST), 'Days Error', 'The input "Days to event" was empty!' & _
                        @CRLF & 'Please enter number of days!!')
                GUICtrlSetState($idEditEvent + 9, $GUI_FOCUS)
                Return
            EndIf
    EndSwitch
    
    ; Create an array to hold the Event values
    Local $aValues[8][2]
    $aValues[0][0] = _GUICtrlListView_GetItemText($idEditEvent + 2, Int(GUICtrlRead($idEditEvent))) ; RowID to update
    $aValues[0][1] = ''
    $aValues[1][0] = 'Name'
    $aValues[1][1] = $sReadName ; Event Name
    $aValues[2][0] = 'Desc'
    $aValues[2][1] = StringReplace(GUICtrlRead($idEditEvent + 6), @CRLF, ' ') ; Get data from edit
    $aValues[3][0] = 'EndDate'
    $aValues[3][1] = StringRegExpReplace($sDTS, "(\d{4})/(\d{2})/(\d{2})(.*)", "$1-$2-$3$4") ; Event end date
    $aValues[4][0] = 'SoundFile'
    $aValues[4][1] = GUICtrlRead($idEditEvent + 15) ; Get sound to play from input sound to play
    $aValues[5][0] = 'PlaySound'
    $aValues[5][1] = (GUICtrlRead($idEditEvent + 17) = $GUI_CHECKED) ? True : False ; To play or not play sound at event end
    $aValues[6][0] = 'PopUp'
    $aValues[6][1] = (GUICtrlRead($idEditEvent + 18) = $GUI_CHECKED) ? True : False ; To show or not to show popup at event end
    $aValues[7][0] = 'Enabled'
    $aValues[7][1] = (GUICtrlRead($idEditEvent + 19) = $GUI_CHECKED) ? True : False ; If enabled or not enabled
    ; Update the DataBase with the new event data
    DBHandle('UpdateEvent', $aValues)
    ; And close the database
    DBHandle('CloseDB', '')
    GUISwitch($hEditEvent)
    ; Close the Edit event gui
    hWnd_Close()
    ; Update the CDD GUI using False, this will tricker the del ctrls to recreate the gui with the updated info
    UpdateGui(False)
    
EndFunc   ;==>idBtn_UpdateEventClick

Func idBtn_EventDeleteClick()
    ; Deletes the selected Event from the Events.ini file and if it's current active in the CountDown GUI
    ; refreshes the gui to remove it from that also
    ; Get the selected Event data
    ; $aData[1] = RowID, [2] = Name, [3] = End Date and [4] = Enabled (True/False)
    Local $aData = StringSplit(StringTrimRight(GUICtrlRead(GUICtrlRead($idDelEvent + 2)), 1), '|')
    If @error Then
        Return SetError(-1)
    EndIf
    ; Then we warn the user that the event will be deletede
    If MsgBox(BitOR($MB_YESNO, $MB_TOPMOST, $MB_SETFOREGROUND, $MB_ICONWARNING), 'Delete Event', 'The Event: "' & $aData[2] & '"' & @CRLF & _
            'with end date: "' & $aData[3] & '"' & @CRLF & 'will be deletede!' & @CRLF & @CRLF & 'Do you want to continue?') = $IDNO Then Return
    
    ; Delete the event from DataBase
    DBHandle('DelEvent', $aData[1])
    DBHandle('CloseDB', '')

    ; Check if the event is active in the CountDownGUI, by checking if it's located in the Event array.
    ; We search for the rowid in the aEvents array, at column 0, and if found we updates the gui
    ; If the deletede event was Enabled we upadte the GUI
    If StringToType($aData[4]) = True Then UpdateGui(False)

    ; Check if Max events is lessere that current enabled events
    If UBound($g_aEvents) - 1 < $g_aSettings[$eSet_Max] Then GUICtrlSetState($MenuItem_AddEvent, $GUI_ENABLE)
EndFunc   ;==>idBtn_EventDeleteClick


Func idBtn_SoundBrowseClick()
    ; Sound file browser
    
    ; Display an open dialog to select a list of file(s).
    Local $iExStyle = BitOR($OFN_PATHMUSTEXIST, $OFN_FILEMUSTEXIST)
    Local $sAudioFile = _WinAPI_OpenFileDlg('', @WorkingDir, 'Audio (*.wav;*.mp3)', 1, '', '', $iExStyle)
    
    ; We only add if there is something to add
    If $sAudioFile <> '' Then
        GUICtrlSetData(@GUI_CtrlId - 1, $sAudioFile)
        GUICtrlSetTip(@GUI_CtrlId - 1, $sAudioFile)
    EndIf

EndFunc   ;==>idBtn_SoundBrowseClick

Func EventListView()
    ; Handle Edit event ListView double clicks
    ; When a user double clicks on an item in the listview, the WM_NOTIFY sends item index
    ; to the $idEditEvent dummy
    ; Error handle
    Local $sitem = _GUICtrlListView_GetItemText($idEditEvent + 2, Int(GUICtrlRead($idEditEvent)))
    If $sitem = '' Then Return SetError(-1)
    ; Get Event data from the DataBase
    Local $aData = DBHandle('GetSingleEvent', $sitem)
    ; Set data to gui
    ; Add the data to the inputs
    GUICtrlSetData($idEditEvent + 4, $aData[1]) ; Add the name to Event Name input
    GUICtrlSetData($idEditEvent + 6, $aData[2]) ; Add Description
    GUICtrlSetData($idEditEvent + 13, $aData[3]) ; Add end date of event
    GUICtrlSetData($idEditEvent + 15, $aData[4]) ; Add the sound
    GUICtrlSetTip($idEditEvent + 15, $aData[4])
    
    ;Update the state of the checkboxes
    CbSetState($idEditEvent + 17, StringToType($aData[5])) ; PlaySound checkbox
    CbSetState($idEditEvent + 18, StringToType($aData[6])) ; Popup Checkbox
    CbSetState($idEditEvent + 19, StringToType($aData[7])) ; Enabled checkbox
    
    ; Enables controls
    GUICtrlSetState($idEditEvent + 4, $GUI_ENABLE) ; Event name
    GUICtrlSetState($idEditEvent + 6, $GUI_ENABLE) ; Event description
    GUICtrlSetState($idEditEvent + 7, $GUI_ENABLE) ; Checkbox choose by date
    GUICtrlSetState($idEditEvent + 13, $GUI_ENABLE) ; Date picker
    GUICtrlSetState($idEditEvent + 15, $GUI_ENABLE) ; Sound to play
    GUICtrlSetState($idEditEvent + 16, $GUI_ENABLE) ; Button Sound Browse
    GUICtrlSetState($idEditEvent + 17, $GUI_ENABLE) ; Checkbox play sound
    GUICtrlSetState($idEditEvent + 18, $GUI_ENABLE) ; Checkbox Popup
    GUICtrlSetState($idEditEvent + 19, $GUI_ENABLE) ; Checkbox Enabled
    GUICtrlSetState($idEditEvent + 20, $GUI_ENABLE) ; Update button
    
EndFunc   ;==>EventListView

Func idCombo_EventsChange()
    ; Here we handle the combo changes for Add events
    
    ; First we read the combo
    Local $sRead = GUICtrlRead($idAddEvent + 2)
    ; Now we get the default event data from the DataBase, using the index +1 of the selected event
    Local $aData = DBHandle('GetSingleDefEvent', _GUICtrlComboBox_GetCurSel($idAddEvent + 2) + 1)
    _ArrayDisplay($aData, 'Selected in combo')
    ; Close the DataBase
    DBHandle('CloseDB', '')

    ; Add the data to the inputs
    GUICtrlSetData($idAddEvent + 4, $aData[0]) ; Add Name of event to input
    GUICtrlSetData($idAddEvent + 6, $aData[1]) ; Add Description to the edit
    GUICtrlSetData($idAddEvent + 9, $aData[2]) ; Add number of days to input
    GUICtrlSetData($idAddEvent + 15, $aData[3]) ; Add sound to input
    GUICtrlSetTip($idAddEvent + 15, $aData[3]) ; Set sound tip (to show full path on hover)
    ; Set the state of Soundplay
    CbSetState($idAddEvent + 17, StringToType($aData[4]))
    ; Set the state of popup checkbox
    CbSetState($idAddEvent + 18, StringToType($aData[5]))

EndFunc   ;==>idCombo_EventsChange

Func UpdateGui($bStart = True)
    ; Adds events to the main gui
    ; Check if we have an event to add to the gui
    If $g_aEvents[0][1] = Null And $bStart = False Then Return ; If we don't have any events
    ; If the function is called with False, we deletes all controls
    If $bStart = False Then
        ; Delete existing controls, so we can recreate them
        For $i = 1 To UBound($g_aEvents) - 1
            GUICtrlDelete($g_idLbl_Event[$i]) ; Delete the Event Name Label
            GUICtrlDelete($g_idLbl_Days[$i]) ; Deletes the label Days Counter
            GUICtrlDelete($g_idLbl_Days[$i] + 1) ; Deletes the label Days
            GUICtrlDelete($g_idLbl_Days[$i] + 2) ; Deletes the label we use as a frame for the gui
            GUICtrlDelete($g_idLbl_Hrs[$i]) ; Deletes the label Hrs counter
            GUICtrlDelete($g_idLbl_Hrs[$i] + 1) ; Deletes the label : after hrs
            GUICtrlDelete($g_idLbl_Min[$i]) ; Deletes the label min counter
            GUICtrlDelete($g_idLbl_Min[$i] + 1) ; Deletes the label : after min
            GUICtrlDelete($g_idLbl_Sec[$i]) ; Deletes the label sec counter
            GUICtrlDelete($g_idLbl_Sec[$i] + 1) ; Deletes the label we use as frame around the time counter
            GUICtrlDelete($g_idLbl_Sec[$i] + 2) ; Deletes the Group we use as spacer
            
        Next
        
    EndIf
    $g_aEvents = DBHandle('GetEvents', $g_iInstance) ; reload the array
    DBHandle('CloseDB', '')
    ; Check if there is any events
    If UBound($g_aEvents) = 1 Then
        $g_aEvents[0][0] = 1
        $g_aEvents[0][1] = Null
        Return
    EndIf

    ; Updates the global GUIHeight
    $g_iGuiHeight = ($g_iSpace * (UBound($g_aEvents) - 1)) + 8
    ; Switch to the CDD gui, else the labels would be created on the last active gui
    GUISwitch($hCountdownDays)
    For $i = 1 To UBound($g_aEvents) - 1
        ; Adds the events to the Countdown gui
        $g_idLbl_Event[$i] = GUICtrlCreateLabel($g_aEvents[$i][$eEvent_Name], 8, 14 + (($i - 1) * $g_iSpace), 119, 20, $SS_CENTER)
        GUICtrlSetFont(-1, 12, 400, 0, "Arial Narrow")
        GUICtrlSetColor(-1, $g_aColors[$eCol_Name]) ; Navy blue
        GUICtrlSetTip(-1, SplitText($g_aEvents[$i][$eEvent_Desc], 45), 'Description:', 1, 1)
        $g_idLbl_Days[$i] = GUICtrlCreateLabel("", 31, 34 + (($i - 1) * $g_iSpace), 32, 20, $SS_RIGHT)
        GUICtrlSetFont(-1, 14, 800, 0, "Arial Narrow")
        GUICtrlCreateLabel("Days", 65, 34 + (($i - 1) * $g_iSpace), 34, 20)
        GUICtrlSetFont(-1, 14, 400, 0, "Arial Narrow")
        GUICtrlSetColor(-1, $g_aColors[$eCol_DaysLbl])
        ; Create a static lable to frame the Time countdown
        GUICtrlCreateLabel("", 16, 56 + (($i - 1) * $g_iSpace), 102, 26, BitOR($SS_GRAYFRAME, $WS_DISABLED, $SS_SUNKEN))
        $g_idLbl_Hrs[$i] = GUICtrlCreateLabel("", 22, 58 + (($i - 1) * $g_iSpace), 18, 20, $SS_CENTER)
        GUICtrlSetFont(-1, 14, 800, 0, "Arial Narrow")
        GUICtrlCreateLabel(":", 46, 58 + (($i - 1) * $g_iSpace), 8, 20)
        GUICtrlSetColor(-1, $g_aColors[$eCol_TimeColon])
        GUICtrlSetFont(-1, 14, 800, 0, "Arial Narrow")
        $g_idLbl_Min[$i] = GUICtrlCreateLabel("", 56, 58 + (($i - 1) * $g_iSpace), 18, 20, $SS_CENTER)
        GUICtrlSetFont(-1, 14, 800, 0, "Arial Narrow")
        GUICtrlCreateLabel(":", 80, 58 + (($i - 1) * $g_iSpace), 8, 20)
        GUICtrlSetColor(-1, $g_aColors[$eCol_TimeColon])
        GUICtrlSetFont(-1, 14, 800, 0, "Arial Narrow")
        $g_idLbl_Sec[$i] = GUICtrlCreateLabel("", 90, 58 + (($i - 1) * $g_iSpace), 18, 20, $SS_CENTER)
        GUICtrlSetFont(-1, 14, 800, 0, "Arial Narrow")
        
        ; We add a horizontal line as a spacer between the events, but only if we have more that one. But we don't add one after the last
        If $i >= 1 And $i < UBound($g_aEvents) - 1 And UBound($g_aEvents) - 1 > 1 Then
            GUICtrlCreateGroup("", 0, 84 + (($i - 1) * $g_iSpace), 135, 9)
            GUICtrlCreateGroup("", -99, -99, 1, 1)
        EndIf
        $g_idLbl_Event[0] = $i
    Next
    ; Resizes the Frame label
    GUICtrlSetPos($idFrame, 0, 0, 136, $g_iGuiHeight + 4)
    ; Get the position of the Countdown gui
    Local $aWinPos = WinGetPos($hCountdownDays)

    ; Updates the height of the Countdown gui, using the pos we got, and the new height using the updated global guiheight
    _WinAPI_SetWindowPos($hCountdownDays, $HWND_NOTOPMOST, $aWinPos[0], $aWinPos[1], 136, $g_iGuiHeight + 4, _
            BitOR($SWP_NOACTIVATE, $SWP_NOMOVE, $SWP_NOZORDER))
    
    ; Finaly we checks if we have exceeded or maxed out the allowed amounts of Events.
    ; If so we disables the add event MenuItem, thereby preventing the user to add more events, until
    ; an Event is either disabled or deleted, making up space for a new one.
    If UBound($g_aEvents) - 1 >= $g_aSettings[$eSet_Max] Then GUICtrlSetState($MenuItem_AddEvent, $GUI_DISABLE)
EndFunc   ;==>UpdateGui

Func CbSetState($iCtrlID, $bEnabled)
    Switch $bEnabled ; Popup checkbox
        Case True
            GUICtrlSetState($iCtrlID, $GUI_CHECKED)
        Case False
            GUICtrlSetState($iCtrlID, $GUI_UNCHECKED)
    EndSwitch
EndFunc   ;==>CbSetState

Func Countdown()
    If $g_aEvents[0][1] = Null Then Return ; If we don't have any events
    For $i = 1 To UBound($g_aEvents) - 1
        ; cycle through events
        Local $iGetSec = _DateDiff('s', _NowCalc(), StringRegExpReplace($g_aEvents[$i][$eEvent_Date], "(\d{4})-(\d{2})-(\d{2})(.*)", "$1/$2/$3$4"))
        
        ; grab seconds of difference from now to future date
        If $iGetSec <= 0 And StringToType($g_aEvents[$i][$eEvent_Enabled]) = True Then
            EventHandle($g_aEvents[$i][$eEvent_RowID], $i)
        EndIf
        Ticks_To_Time($iGetSec, $g_iDays, $g_iHours, $g_iMins, $g_iSecs)
        If @error Then
            ; If time is up, we update days,hours, min and sec. This it to prevent false time/day update of the event, sins TTT uses byref and
            ; if we don't update the var's the event counter would be equal to the previous event time.
            $g_iDays = 0
            $g_iHours = '00'
            $g_iMins = '00'
            $g_iSecs = '00'
        EndIf
        ; convert seconds to days/hours/minutes/seconds
        
        ; set color and data
        Switch $g_iDays
            Case 0 To 5
                GUICtrlSetDataAndColor($g_idLbl_Days[$i], $g_iDays, 1) ; Red
            Case 6 To 10
                GUICtrlSetDataAndColor($g_idLbl_Days[$i], $g_iDays, 2) ; Yellow
            Case 11 To 15
                GUICtrlSetDataAndColor($g_idLbl_Days[$i], $g_iDays, 3) ; Green
            Case Else
                GUICtrlSetDataAndColor($g_idLbl_Days[$i], $g_iDays, 0) ; Black
        EndSwitch
        ; If days = 0 we want to change the timer colors
        If $g_iDays = 0 Then
            Switch $g_iHours
                Case 0 To 6
                    GUICtrlSetDataAndColor($g_idLbl_Hrs[$i], $g_iHours, 5) ; Red
                    GUICtrlSetDataAndColor($g_idLbl_Min[$i], $g_iMins, 5) ; Red
                    GUICtrlSetDataAndColor($g_idLbl_Sec[$i], $g_iSecs, 5) ; Red
                Case 7 To 12
                    GUICtrlSetDataAndColor($g_idLbl_Hrs[$i], $g_iHours, 6) ; Yellow
                    GUICtrlSetDataAndColor($g_idLbl_Min[$i], $g_iMins, 6) ; Yellow
                    GUICtrlSetDataAndColor($g_idLbl_Sec[$i], $g_iSecs, 6) ; Yellow
                Case 13 To 23
                    GUICtrlSetDataAndColor($g_idLbl_Hrs[$i], $g_iHours, 7) ; Green
                    GUICtrlSetDataAndColor($g_idLbl_Min[$i], $g_iMins, 7) ; Green
                    GUICtrlSetDataAndColor($g_idLbl_Sec[$i], $g_iSecs, 7) ; Green
            EndSwitch
        Else ; If not we just keep them black
            GUICtrlSetDataAndColor($g_idLbl_Hrs[$i], $g_iHours, 4) ; Black
            GUICtrlSetDataAndColor($g_idLbl_Min[$i], $g_iMins, 4) ; Black
            GUICtrlSetDataAndColor($g_idLbl_Sec[$i], $g_iSecs, 4) ; Black
        EndIf
    Next
EndFunc   ;==>Countdown

Func EventHandle($iRowID, $iIndex)
    ; Here we handles the event when it's time is up o_O
    ConsoleWrite(@CRLF & 'Event Handle' & @CRLF)
    ; First we disable the event, to prevent it from caling this function more than once.
    $g_aEvents[$iIndex][$eEvent_Enabled] = False

    DBHandle('UpdateEventStatus', 'Enabled|False|' & $iRowID)
    DBHandle('CloseDB', '')
    ; Set background label of the event to Yellow and text to Red - Indicate that the event is up
    GUICtrlSetColor($g_idLbl_Event[$iIndex], $g_aColors[$eCol_EventUp])
    GUICtrlSetBkColor($g_idLbl_Event[$iIndex], $g_aColors[$eCol_EventUpBk])
    
    ; Check if a sound should be played
    If StringToType($g_aEvents[$iIndex][$eEvent_SoundPlay]) = True Then SoundPlay($g_aEvents[$iIndex][$eEvent_SoundFile])
    
    ; Check if a popup should be displayed
    If StringToType($g_aEvents[$iIndex][$eEvent_Pop]) = True Then
        ; Disable the on event mode, else the GuiGetMsg won't work
        Opt("GUIOnEventMode", 0)
        ; Create the popup window
        Local $iStyle = BitOR($WS_SYSMENU, $WS_POPUP, $DS_SETFOREGROUND, $WS_CAPTION)
        Local $iExStyle = BitOR($WS_EX_TOPMOST, $WS_EX_TOOLWINDOW)
        Local $hPopup = GUICreate($g_aEvents[$iIndex][$eEvent_Name], 405, 285, Default, Default, $iStyle, $iExStyle)
        Local $idEdit_Popup = GUICtrlCreateEdit("", 11, 8, 385, 233, BitOR($ES_CENTER, $ES_READONLY, $ES_WANTRETURN, $WS_VSCROLL))
        ; Set the Event description test to the edit
        GUICtrlSetData(-1, @CRLF & SplitText($g_aEvents[$iIndex][$eEvent_Desc]), 45)
        GUICtrlSetBkColor(-1, $g_aColors[$eCol_GuiBk])
        GUICtrlSetFont(-1, 18, 800, 0, "Arial Narrow") ; Boost the font size
        Local $idBtn_OK = GUICtrlCreateButton("OK", 165, 256, 75, 21, $BS_DEFPUSHBUTTON)
        GUISetState(@SW_SHOW)

        While 1
            Local $nMsg = GUIGetMsg()
            Switch $nMsg
                Case $GUI_EVENT_CLOSE, $idBtn_OK
                    SoundPlay('') ; Kill the sound if any
                    GUIDelete($hPopup) ; Delete the gui
                    ExitLoop ; And exit loop
            EndSwitch
        WEnd
        Opt("GUIOnEventMode", 1) ; Reenable OnEventMode
    EndIf
    
    GUICtrlSetOnEvent($g_idLbl_Event[$iIndex], 'Click_Main')
EndFunc   ;==>EventHandle

Func DBHandle($sHandle, ByRef $vData)
    ConsoleWrite(@CRLF & 'DBHandle call = ' & $sHandle & @CRLF)
    ; Here we handle all SQLite handles
    ; Open/Close DataBase, Update/Change Settings, Add/Edit/Delete Events Add/Delete Default Events
    
    ; Create a static var to handle open close of the database
    Local Static $bOpen = True
    If $bOpen Then
        $bOpen = False ; Change the static to False, so we don't continues to open the database - when it hasn't been closed
        Local $g_hDB = _SQLite_Open($g_sDBFile) ; Open the SQLite database
        If @error Then
            MsgBox($g_iMBErr, "SQLite Error", "Can't open Database!")
            Exit -1
        EndIf
    EndIf
    ; Switch thru the handles
    Switch $sHandle
        Case 'ByString'
            SQLite_QuerryArrayByString($vData)
        Case 'GetSet'
            ; Getting settings from the DB
            Local $aData2D = SQLite_QuerryArray('Settings', $vData)
            ; Error checker to prevent empty array
            If UBound($aData2D) = 1 Then
                Return SetError(-1)
            EndIf
            ;Stripping first row, colum 0 and 1 (RowID and Instance) and convert the array to 1D
            Local $aData1D[0]
            For $i = 0 To UBound($aData2D, $UBOUND_COLUMNS) - 1
                _ArrayAdd($aData1D, StringToType($aData2D[1][$i]))
            Next
            ; Return the 1D Settings array
            Return $aData1D
        Case 'GetColors'
            ; Get color settings
            Local $aData2D = SQLite_QuerryArray('Colors', $vData)
            If UBound($aData2D) = 1 Then
                Return SetError(-1)
            EndIf
            ;Stripping first row, colum 0 and 1 (RowID and Instance) and convert the array to 1D
            Local $aData1D[0]
            For $i = 0 To UBound($aData2D, $UBOUND_COLUMNS) - 1
                _ArrayAdd($aData1D, $aData2D[1][$i])
            Next
            ; Return the 1D Settings array
            Return $aData1D
        Case 'UpdateSet'
            ; Updates the settings and colors in the DataBase
            ; First we creates a 2D array for Settings and Colors
            Local $aSetCol = StringSplit($g_aSettings[$eSet_RowID] & '|Instance|Max|Remember|SoundPlay|PopUp|Start|Lang|SoundFile|PosLeft|PosTop', '|')
            Local $aColCol = StringSplit($g_aColors[$eCol_RowID] & '|Instance|GuiBk|DragLbl|Name|DaysCount0|DaysCount1|DaysCount2|DaysCount3|' & _
                    'DaysLbl|Time0|Time1|Time2|Time3|TimeColon|EventUp|EventUpBk', '|')
            Local $aSet[$aSetCol[0]][2], $aCol[$aColCol[0]][2]
            ; Create Settings 2D array
            For $i = 0 To $aSetCol[0] - 1
                $aSet[$i][0] = $aSetCol[$i + 1]
                $aSet[$i][1] = $g_aSettings[$i]
            Next
            ; Create colors 2D array
            For $i = 0 To $aColCol[0] - 1
                $aCol[$i][0] = $aColCol[$i + 1]
                $aCol[$i][1] = $g_aColors[$i]
            Next
            ; Update the DataBase
            SQLite_UpdateByArray('Settings', $aSet)
            SQLite_UpdateByArray('Colors', $aCol)
        Case 'UpdatePos'
            ; Update the Position
            SQLite_UpdateByArray('Settings', $vData)
        Case 'GetEvents'
            ; Get all enabled events, for the current instance
            Return SQLite_QuerryArray('EventsEnabled', $vData)
        Case 'GetAllEvents'
            ; Get all events for this instance, enabled and disabled
            Local $aData = SQLite_QuerryArray('Events', $vData)
            If UBound($aData) = 1 Then
                Return SetError(-1)
            Else
                Return $aData
            EndIf
        Case 'GetSingleEvent'
            ; Get a single event
            Local $aData = SQLite_QuerryRow('Events', $vData)
            If UBound($aData) = 0 Then
                Return SetError(-1)
            Else
                Return $aData
            EndIf
        Case 'AddEvent'
            ; Add an event to the DataBase
            SQLite_AddByArray('Events', $vData)
        Case 'DelEvent'
            ; Delete a single event.
            SQLite_DelSingle('Events', $vData)
        Case 'UpdateEvent'
            ; Update a single event
            SQLite_UpdateByArray('Events', $vData)
        Case 'UpdateEventStatus'
            ; Updates a single coloum
            Local $aData = StringSplit($vData, '|')
            SQLite_UpdateSingle('Events', $aData[1], StringToType($aData[2]), $aData[3])
        Case 'AddDefEvent'
            ; Adds a single default event to the DataBase
            SQLite_AddByArray('DefEvents', $vData)
        Case 'UpdateDefEvent'
            ; Updates a singel default event in the DataBase
            SQLite_UpdateByArray('DefEvents', $vData)
        Case 'GetDefEvents'
            ; Get all default evnets from the DataBase
            Return _ArrayExtract(SQLite_QuerryArray('DefEvents', ''), 1)
        Case 'GetSingleDefEvent'
            ; Get a single default event from the DataBase
            Return SQLite_QuerryRow('DefEvents', $vData)
        Case 'DelSingleDefEvent'
            ; Deletes a single Default event from teh DataBase
            SQLite_DelSingle('DefEvents', $vData)
        Case 'UpdateSingleSet'
            ; Updates a single coloum
            Local $aData = StringSplit($vData, '|')
            SQLite_UpdateSingle('Settings', $aData[1], StringToType($aData[2]), $g_aSettings[$eSet_RowID])
            ContinueCase ; We continues case so the database is closed
        Case 'CloseDB'
            ConsoleWrite(@CRLF & 'DataBase was closed' & @CRLF)
            $bOpen = True ; Set static to True, so when the function is called next time, the datbase is opened
            _SQLite_Close() ; Close the database
        Case 'VACUUM'
            SQLite_Vacuum()
    EndSwitch

EndFunc   ;==>DBHandle
Func SQLite_QuerryArrayByString($sString)
    Local $aResult, $iRows, $iColumns, $iRval
    
        $iRval = _SQLite_GetTable2D(-1, $sString, $aResult, $iRows, $iColumns)

    If $iRval = $SQLITE_OK Then
        Return $aResult
    EndIf
    MsgBox(0, 'title', _SQLite_ErrMsg())
    
EndFunc
Func SQLite_UpdateSingle($sTable, $sColum, $vData, $iRowID)
    ; We update a single columm by using the colum name and the rowid
    ; First we check if the data we should update is Boolean, we check this course if we try to fastescape
    ; a boolean value, sqlite gives an error
    If IsBool($vData) Then
        $vData = "'" & $vData & "'"
    Else
        $vData = _SQLite_FastEscape($vData) ; It's not boolean
    EndIf
    ; Update Database
    _SQLite_Exec(-1, "UPDATE " & $sTable & " SET " & $sColum & " = " & $vData & " WHERE rowid=" & $iRowID & ";")
    
EndFunc   ;==>SQLite_UpdateSingle

Func SQLite_AddByArray($sTable, $aData)
    ; Add data to the DataBase using an array
    
    For $i = 0 To UBound($aData) - 1
        ; Create a string of data to add to the database
        Local $sData
        ; First we check if that data it boolean
        If IsBool($aData[$i]) Then
            ; The data was boolean, so we update without using fastecsape
            $sData &= "'" & $aData[$i] & "', "
        Else
            $sData &= _SQLite_FastEscape($aData[$i]) & ', '

        EndIf
    Next
    _SQLite_Exec(-1, "INSERT INTO " & $sTable & " VALUES ( " & StringTrimRight($sData, 2) & ");")
EndFunc   ;==>SQLite_AddByArray

Func SQLite_UpdateByArray($sTable, ByRef $aData)
    ; Update DataBase using a 2d array, where [0] is column name and [1] is the data to set
    Local $iRowID = $aData[0][0]
    For $i = 1 To UBound($aData) - 1
        ; First we check if that data it boolean
        If IsBool($aData[$i][1]) Then
            ; The data was boolean, so we update without using fastecsape
            _SQLite_Exec(-1, "UPDATE " & $sTable & " SET " & $aData[$i][0] & " = '" & $aData[$i][1] & "' WHERE rowid=" & $iRowID & ";")
        Else
            ; We update using fastescape
            _SQLite_Exec(-1, "UPDATE " & $sTable & " SET " & $aData[$i][0] & " = " & _SQLite_FastEscape($aData[$i][1]) & " WHERE rowid=" & $iRowID & ";")
        EndIf
    Next
EndFunc   ;==>SQLite_UpdateByArray

Func SQLite_DelSingle($sTable, $iRowID)
    ; Delete a singel row from the table
    _SQLite_Exec(-1, "DELETE FROM " & $sTable & " WHERE rowid=" & $iRowID & ";")

EndFunc   ;==>SQLite_DelSingle

Func SQLite_DelByInstance($sTable, $iInst)
    ; Delete a singel row from the table
    _SQLite_Exec(-1, "DELETE FROM " & $sTable & " WHERE Instance=" & $iInst & ";")

EndFunc   ;==>SQLite_DelSingle

Func SQLite_Vacuum()
    ; Reset the rowid values, and rebuild the index from the scratch
    _SQLite_Exec(-1, "VACUUM;")
EndFunc   ;==>SQLite_Vacuum

Func SQLite_QuerryArray($sTable, $iInst)
    Local $aResult, $iRows, $iColumns, $iRval
    If $sTable = 'EventsEnabled' Then
        $iRval = _SQLite_GetTable2D(-1, 'SELECT rowid,* FROM Events WHERE Instance=' & $iInst & " AND Enabled='True';", $aResult, $iRows, $iColumns)
    ElseIf $sTable = 'DefEvents' Then
        $iRval = _SQLite_GetTable2D(-1, 'SELECT rowid,* FROM "' & $sTable & '";', $aResult, $iRows, $iColumns)
    Else
        $iRval = _SQLite_GetTable2D(-1, 'SELECT rowid,* FROM "' & $sTable & '" WHERE Instance=' & $iInst & ';', $aResult, $iRows, $iColumns)
    EndIf
    If $iRval = $SQLITE_OK Then
        Return $aResult
    EndIf
    MsgBox(0, 'title', _SQLite_ErrMsg())
EndFunc   ;==>SQLite_QuerryArray

Func SQLite_QuerryRow($sTable, $iRowID)
    Local $aRow
    _SQLite_QuerySingleRow(-1, "SELECT * FROM " & $sTable & " WHERE rowid=" & $iRowID & ";", $aRow) ; Select single row
    Return $aRow
EndFunc   ;==>SQLite_QuerryRow

Func SQLite_QuerrySingle($sTable, $sColum, $iRowID)
    Local $aRow
    _SQLite_QuerySingleRow(-1, "SELECT " & $sColum & " FROM " & $sTable & " WHERE rowid=" & $iRowID & ";", $aRow) ; Select single field !
    Return $aRow
EndFunc   ;==>SQLite_QuerrySingle

Func CreateDB()
    ; Create DataBase
    Local $sTables
    $sTables &= 'CREATE TABLE [Colors]('
    $sTables &= '[Instance] INT,'
    $sTables &= '[GuiBk] VARCHAR,'
    $sTables &= '[DragLbl] VARCHAR,'
    $sTables &= '[Name] VARCHAR,'
    $sTables &= '[DaysCount0] VARCHAR,'
    $sTables &= '[DaysCount1] VARCHAR,'
    $sTables &= '[DaysCount2] VARCHAR,'
    $sTables &= '[DaysCount3] VARCHAR,'
    $sTables &= '[DaysLbl] VARCHAR,'
    $sTables &= '[Time0] VARCHAR,'
    $sTables &= '[Time1] VARCHAR,'
    $sTables &= '[Time2] VARCHAR,'
    $sTables &= '[Time3] VARCHAR,'
    $sTables &= '[TimeColon] VARCHAR,'
    $sTables &= '[EventUp] VARCHAR,'
    $sTables &= '[EventUpBk] VARCHAR);'

    $sTables &= 'CREATE TABLE[Events]('
    $sTables &= '[Instance] INT,'
    $sTables &= '[Name] VARCHAR,'
    $sTables &= '[Desc] VARCHAR,'
    $sTables &= '[EndDate] DATETIME,'
    $sTables &= '[SoundFile] VARCHAR,'
    $sTables &= '[PlaySound] BOOLEAN,'
    $sTables &= '[PopUp] BOOLEAN,'
    $sTables &= '[Enabled] BOOLEAN);'

    $sTables &= 'CREATE TABLE[Position]('
    $sTables &= '[Instance] INT,'
    $sTables &= '[PosLeft] INT,'
    $sTables &= '[PosTop] INT,'
    $sTables &= '[Pin] BOOLEAN);'

    $sTables &= 'CREATE TABLE[DefEvents]('
    $sTables &= '[Name] VARCHAR UNIQUE ON CONFLICT REPLACE,'
    $sTables &= '[Desc] VARCHAR,'
    $sTables &= '[Days] INT,'
    $sTables &= '[SoundFile] VARCHAR,'
    $sTables &= '[PlaySound] BOOLEAN,'
    $sTables &= '[PopUp] BOOLEAN);'

    ; Insert default data
    Local $sDefData
    $sDefData &= "INSERT INTO Position VALUES ('0', -1, -1, 'False');"
    $sDefData &= "INSERT INTO Colors VALUES ('0', '0x4E4E4E','0x808080','0xFFFFFF', '0x000000', '0xFF0000', " & _
            "'0xFFFF00', '0x008000', '0x000000', '0x000000','0xFF0000', '0xFFFF00', '0x008000', '0x000000', '0xFF0000', '0xFFFF00');"
    _SQLite_Open(@ScriptDir & '\Data.db') ; Create the DataBase
    If @error Then
        Return SetError(-1)
    EndIf
    _SQLite_Exec(-1, $sTables)
    If @error Then
        Return SetError(-1)
    EndIf
    _SQLite_Exec(-1, $sDefData)
    If @error Then
        Return SetError(-1)
    EndIf
    _SQLite_Close()
    If @error Then
        Return SetError(-1)
    EndIf
EndFunc   ;==>CreateDB

Func Ticks_To_Time($iSeconds, ByRef $idays, ByRef $iHours, ByRef $iMins, ByRef $iSecs)
    ; second conversion.

    ; modified: added days. added format style, to use 00 for time
    If Number($iSeconds) > 0 Then
        $idays = Int($iSeconds / 86400)

        $iSeconds = Mod($iSeconds, 86400)
        $iHours = StringFormat("%02d", Int($iSeconds / 3600))

        $iSeconds = Mod($iSeconds, 3600)
        $iMins = StringFormat("%02d", Int($iSeconds / 60))

        $iSecs = StringFormat("%02d", Mod($iSeconds, 60))
        Return 1
    Else
        Return SetError(1, 0, 0)
    EndIf
EndFunc   ;==>Ticks_To_Time

Func GUICtrlSetDataAndColor($hWnd, $iCount, $iColor)
    ; Set Day(s), Hour(s), Min(s), Sec(s) and color to the countdown labels
    Local $dColor

    Switch $iColor ; Check if we chould use a color
        Case 0 ; Black <- Default color
            $dColor = $g_aColors[$eCol_Days0]
        Case 1 ; Red
            $dColor = $g_aColors[$eCol_Days1]
        Case 2 ; Yellow
            $dColor = $g_aColors[$eCol_Days2]
        Case 3 ; Green
            $dColor = $g_aColors[$eCol_Days3]
        Case 4
            $dColor = $g_aColors[$eCol_Time0]
        Case 5
            $dColor = $g_aColors[$eCol_Time1]
        Case 6
            $dColor = $g_aColors[$eCol_Time2]
        Case 7
            $dColor = $g_aColors[$eCol_Time3]
    EndSwitch

    If GUICtrlRead($hWnd) <> $iCount Or GUICtrlRead($hWnd) = '' Then
        ; if data is different then change. helps with flickering
        GUICtrlSetData($hWnd, $iCount)
        GUICtrlSetColor($hWnd, $dColor)
    EndIf

EndFunc   ;==>GUICtrlSetDataAndColor

Func CalcEndDate($idays, $sTime)
    ; Calculates a new date by adding a specified number of Days to an initial date
    Return _DateAdd('D', $idays, @YEAR & '/' & @MON & '/' & @MDAY & ' ' & $sTime)
EndFunc   ;==>CalcEndDate


Func StringToType(ByRef $vData)
    ; Converts a string to bool, Number or KeyWord
    Local $aData = StringRegExp($vData, "(?i)\bTrue\b|\bFalse\b|\bNull\b|\bDefault\b", 3)
    If Not IsArray($aData) Then Return $vData
    Switch $aData[0]
        Case 'True'
            Return True
        Case 'False'
            Return False
        Case 'Null'
            Return Null
        Case 'Default'
            Return Default
        Case Else
            Return Int($aData[0])
    EndSwitch
EndFunc   ;==>StringToType

Func SplitText($sString, $iLenght = 45)
    #cs
        This splits a large text up into cunks at N lengt, at the last space within the nLength specified, and seperated with a @CRLF
        eg. 'A child asked his father, "How were people born?" So his father said, "Adam and Eve made babies, then their babies became adults and made babies, and so on."
        Would be formated as this:
        A child asked his father, "How were people born?" So his father said, "Adam and Eve
        made babies, then their babies became adults and made babies, and so on."
    #ce
    Local $sResult = StringRegExpReplace($sString, ".{1," & $iLenght - 1 & "}\K(\s{1,2}|$)", @CRLF)
    Return $sResult
EndFunc   ;==>SplitText

Func WM_NOTIFY($hWnd, $iMsg, $iwParam, $ilParam)
    #forceref $hWnd, $iMsg, $iwParam

    Local $hWndFrom, $iIDFrom, $iCode, $tNMHDR, $hWndListView_EditEvent, $tInfo, $iRowID, $aData
    $hWndListView_EditEvent = GUICtrlGetHandle($idEditEvent + 2)
    $tNMHDR = DllStructCreate($tagNMHDR, $ilParam)
    $hWndFrom = HWnd(DllStructGetData($tNMHDR, "hWndFrom"))
    $iIDFrom = DllStructGetData($tNMHDR, "IDFrom")
    $iCode = DllStructGetData($tNMHDR, "Code")
    Switch $hWndFrom
        Case $hWndListView_EditEvent
            Switch $iCode
                Case $NM_DBLCLK ; Sent by a list-view control when the user double-clicks an item with the left mouse button
                    $tInfo = DllStructCreate($tagNMITEMACTIVATE, $ilParam)
                    ; Get index of selected Event, and call the listview handle
                    GUICtrlSendToDummy($idEditEvent, DllStructGetData($tInfo, "Index"))
            EndSwitch

    EndSwitch
    Return $GUI_RUNDEFMSG
EndFunc   ;==>WM_NOTIFY

Other suggestions, on how to make my code more effective, is also welcome :)

 

Cheers
/Rex

Edited by Rex
Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...