Jump to content
Sign in to follow this  
anybastard

Select file or folder

Recommended Posts

anybastard

Hi guys ,

for a my program i need to select files or folders

for the files i found -> FileOpenDialog

and

for the folders i found -> FileSelectFolder

My question is ...exist a single function to do this ( select a file or a folder ) ?

Thanks so much for your help

Regards

An1B

Share this post


Link to post
Share on other sites
Melba23

anybastard,

There is no native AutoIt function to do this. ;)

However, here is a much simplified version of my ChooseFileFolder UDF which does the job: :)

#include-once

; #INDEX# ============================================================================================================
; Title .........: FileFolderSelector
; AutoIt Version : 3.3 +
; Language ......: English
; Description ...: Allows selection of files or folders from within a defined path
; Remarks .......: - Requires Melba23 UDF: RecFileListToArray.au3
; Author ........: Melba23
; ====================================================================================================================

;#AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6
;Opt("MustDeclareVars", 1)

; #INCLUDES# =========================================================================================================
#include <GuiTreeView.au3>
#include <RecFileListToArray.au3>

; #GLOBAL VARIABLES# =================================================================================================
Global $fFilFol_DblClk, $aFilFol_Index

; #CURRENT# ==========================================================================================================
; _FilFol_Choose:            Creates a dialog to chose files or folders within a specified path
; _FilFol_RegMsg:            Register WM_NOTIFY to enable double clicks on TreeView
; ====================================================================================================================

; #INTERNAL_USE_ONLY#=================================================================================================
; _FilFol_TV_Fill:     Fills a TreeView with the selected folder structure
; _FilFol_ListFiles:   Adds files to an existing folder structure
; _FilFol_GetSel:      Retrieves selected TreeView item
; ====================================================================================================================

; #FUNCTION# =========================================================================================================
; Name...........: _FilFol_Choose
; Description ...: Shows TV of folder structure and allows election of a file or folder
; Syntax.........: _FilFol_Choose ($sTitle, $iW, $iH, $iX, $iY, $sRoot)
; Parameters ....: $sTitle            - Title of dialog
;                  $iW, $iH, $iX, $iY - Width, Height, Left, Top parameters for dialog
;                  $sRoot             - Path tree to display
; Requirement(s).: v3.3 +
; Return values .: Success: String containing selected item
;                  Failure: Returns "" and sets @error as follows:
;                      1 = Path does not exist
;                      2 = Dialog creation failure
;                      3 = Cancel button or GUI [X] pressed
; Author ........: Melba23
; Modified ......:
; Remarks .......:
; Example........: Yes
;=====================================================================================================================
Func _FilFol_Choose($sTitle, $iW, $iH, $iX, $iY, $sRoot)

    ; Check path
    If $sRoot <> "" Then
        If Not FileExists($sRoot) Then Return SetError(1, 0, "")
        If StringRight($sRoot, 1) <> "\" Then $sRoot &= "\"
    Else
        Return SetError(1, 0, "")
    EndIf

    Local $hTreeView, $hTreeView_Handle, $hTV_GUI, $hTreeView_Label, $hTreeView_Progress, $sSelectedPath

    ; Check for width and height minima and set button size
    Local $iButton_Width
    If $iW < 130 Then $iW = 130
    $iButton_Width = Int(($iW - 30) / 2)
    If $iButton_Width > 80 Then $iButton_Width = 80
    If $iH < 300 Then $iH = 300

    ; Create dialog
    Local $hFilFol_Win = GUICreate($sTitle, $iW, $iH, $iX, $iY, 0x80C80000) ; BitOR($WS_POPUPWINDOW, $WS_CAPTION)
    If @error Then Return SetError(2, 0, "")
    GUISetBkColor(0xCECECE)

    ; Create buttons
    Local $hSel_Button = GUICtrlCreateButton("Select", $iW - ($iButton_Width + 10), $iH - 40, $iButton_Width, 30)
    Local $hCan_Button = GUICtrlCreateButton("Cancel", $iW - ($iButton_Width + 10) * 2, $iH - 40, $iButton_Width, 30)

    ; Create controls
    ; Create TV and hide
    $hTreeView = GUICtrlCreateTreeView(10, 10, $iW - 20, $iH - 60)
    $hTreeView_Handle = GUICtrlGetHandle($hTreeView)
    GUICtrlSetState(-1, 32) ; $GUI_HIDE
    ; Create Indexing label and progress
    $hTreeView_Label = GUICtrlCreateLabel("Indexing..." & @CRLF & "Please be patient", ($iW - 150) / 2, 20, 100, 30)
    $hTreeView_Progress = GUICtrlCreateProgress(($iW - 150) / 2, 60, 150, 10, 0x00000008); $PBS_MARQUEE
    GUICtrlSendMsg(-1, 0x40A, True, 50) ; $PBM_SETMARQUEE

    GUISetState()

    ; IFill TV
    _FilFol_TV_Fill($hFilFol_Win, $hTV_GUI, $hTreeView, $sRoot)
    ; Show TV
    GUICtrlSetState($hTreeView, 16) ; $GUI_SHOW
    ; Delete label and progress
    GUICtrlDelete($hTreeView_Label)
    GUICtrlDelete($hTreeView_Progress)

    ; Change to MessageLoop mode
    Local $nOldOpt = Opt('GUIOnEventMode', 0)

    While 1

        Local $aMsg = GUIGetMsg(1)

        If $aMsg[1] = $hFilFol_Win Then

            Switch $aMsg[0]
                Case $hSel_Button
                    ; Get the selected path
                    $sSelectedPath = _FilFol_GetSel($hTreeView_Handle, $sRoot, _GUICtrlTreeView_GetSelection($hTreeView))
                    If $sSelectedPath Then
                        GUIDelete($hFilFol_Win)
                        ; Restore previous mode
                        Opt('GUIOnEventMode', $nOldOpt)
                        ; Return valid path
                        Return $sSelectedPath
                    EndIf
                Case $hCan_Button, -3 ; $GUI_EVENT_CLOSE
                    GUIDelete($hFilFol_Win)
                    ; Restore previous mode
                    Opt('GUIOnEventMode', $nOldOpt)
                    Return SetError(3, 0, "")
            EndSwitch
        EndIf

        ; Check if mouse has doubleclicked in TreeView
        If $fFilFol_DblClk = $hTreeView_Handle Then
            ; Reset flag
            $fFilFol_DblClk = 0
            ; Get the selected path
            $sSelectedPath = _FilFol_GetSel($hTreeView_Handle, $sRoot)
            If $sSelectedPath Then
                GUIDelete($hFilFol_Win)
                ; Restore previous mode
                Opt('GUIOnEventMode', $nOldOpt)
                ; Return valid path
                Return $sSelectedPath
            EndIf
        EndIf

    WEnd

EndFunc   ;==>_FilFol_Choose

; #FUNCTION# =========================================================================================================
; Name...........: _FilFol_RegMsg
; Description ...: Registers WM_NOTIFY to enable double clicks on TreeView
; Syntax.........: _FilFol_RegMsg()
; Parameteres....: None
; Requirement(s).: v3.3 +
; Return values .: Success: 1
;                  Failure: 0
; Author ........: Melba23
; Modified ......:
; Remarks .......: If the script already has a WM_NOTIFY handler then call the _FilFol_WM_NOTIFY_Handler function
;                  from within it
; Example........: Yes
;=====================================================================================================================
Func _FilFol_RegMsg()

    Return GUIRegisterMsg(0x004E, "_FilFol_WM_NOTIFY_Handler") ; $WM_NOTIFY

EndFunc   ;==>_FilFol_RegMsg

; #FUNCTION# =========================================================================================================
; Name...........: _FilFol_WM_NOTIFY_Handler
; Description ...: Windows message handler for WM_NOTIFY
; Syntax.........: _FilFol_WM_NOTIFY_Handler($hWnd, $iMsg, $wParam, $lParam)
; Requirement(s).: v3.3 +
; Return values .: None
; Author ........: Melba23
; Modified ......:
; Remarks .......: If a WM_NOTIFY handler already registered, then call this function from within that handler
; Example........: Yes
;=====================================================================================================================
Func _FilFol_WM_NOTIFY_Handler($hWnd, $iMsg, $wParam, $lParam)

    #forceref $hWnd, $iMsg, $wParam

    Local $tStruct = DllStructCreate("hwnd hWndFrom;uint_ptr IDFrom;int Code", $lParam)
    Switch DllStructGetData($tStruct, "Code")
        Case -3 ; $NM_DBLCLK
            $fFilFol_DblClk = DllStructGetData($tStruct, "hWndFrom")
    EndSwitch

EndFunc   ;==>_FilFol_WM_NOTIFY_Handler

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: _FilFol_TV_Fill
; Description ...: Fills a TreeView with the selected folder structure to allow folder selection.
; Author ........: Melba23
; Remarks .......:
; ===============================================================================================================================
Func _FilFol_TV_Fill($hFilFol_Win, $hTV_GUI, $hTreeView, $sRoot)

    Local $aLevel[100], $iLevel, $aFilFol_Index, $sFullFolderpath, $sFolderName

    ; Switch to correct GUI
    GUISwitch($hTV_GUI)
    ; Set TV ControlID
    $aLevel[0] = $hTreeView

    ; Create folder array
    $aFilFol_Index = _RecFileListToArray($sRoot, "*", 2, 1, 1, 1, "$*;System Volume Information;RECYCLED;_Restore")

    ; Add root files
    _FilFol_ListFiles($sRoot, $aLevel[0])
    ; Add folders
    For $i = 1 To $aFilFol_Index[0]
        $sFullFolderpath = $aFilFol_Index[$i]
        ; Count \
        StringRegExpReplace($sFullFolderpath, "\\", "")
        $iLevel = @extended
        ; Extract folder name from path
        $sFolderName = StringRegExpReplace($sFullFolderpath, "(.*\\|^)(.*)\\", "$2")
        ; Add to TV and store item ControlID
        $aLevel[$iLevel] = GUICtrlCreateTreeViewItem($sFolderName, $aLevel[$iLevel - 1])
        ; Add files within folder
        _FilFol_ListFiles($sRoot & $aFilFol_Index[$i], $aLevel[$iLevel])
    Next

    ; Switch back to main dialog
    GUISwitch($hFilFol_Win)

EndFunc   ;==>_FilFol_TV_Fill

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: _FilFol_ListFiles
; Description ...: Adds files to an existing folder structure to allow file selection.
; Author ........: Melba23
; Remarks .......:
; ===============================================================================================================================
Func _FilFol_ListFiles($sFolderPath, $hTreeView_Parent)

    Local $sFileName

    Local $aFileArray = _RecFileListToArray($sFolderPath, "*", 1, 0, 1, 0)
    If IsArray($aFileArray) Then
        For $j = 1 To $aFileArray[0]
            $sFileName = $aFileArray[$j]
            GUICtrlCreateTreeViewItem($sFileName, $hTreeView_Parent)
        Next
    EndIf

EndFunc   ;==>_FilFol_ListFiles

; #INTERNAL_USE_ONLY# ===========================================================================================================
; Name...........: _FilFol_GetSel
; Description ...: Retrieves selected TreeView item and adds trailing \ to folders
; Author ........: Melba23
; Remarks .......:
; ===============================================================================================================================
Func _FilFol_GetSel($hTreeView_Handle, $sRoot, $hTreeView_Item = 0)

    Local $sSelection = $sRoot & StringReplace(_GUICtrlTreeView_GetTree($hTreeView_Handle, $hTreeView_Item), "|", "\")

    If StringInStr(FileGetAttrib($sSelection), "D") Then
        $sSelection &= "\"
    EndIf

    Return $sSelection

EndFunc   ;==>_FilFol_GetSel

Just save it as FilFol.au3 in a folder and then run this example from the same folder - try to pick a smallish folder or you will wait a long time: ;)

#include "FilFol.au3"
ConsoleWrite(_FilFol_Choose("Example", 500, 500, 100, 100, @ScriptDir) & @CRLF)

Folders are returned with a trailing \ to help you distinguish them.

I realise that it takes a fair time to load the tree - if you want it faster, then write your own function! :graduated:

M23


Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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  

×