Maybe it is of use fro someone
Code: Select all
; initial idea in AHK V1: https://www.autohotkey.com/board/topic/13239-nested-and-sorted-folder-structure-for-menus/
; creates a menu with submenus of a folder structure in recursive way
; adds icons to all menu entries: https://www.autohotkey.com/boards/viewtopic.php?t=77201
; creates a list of all file paths within the folders, using `n between entries
; - menuObj: the menu object to be filled
; - FolderPath: path to the folder that should be added to the menu
; - HandlerFunctionName: the name of the function to be called when the menu entry is selected
; returns a list of all file paths within the folder, separated by `n
AddFolderStructureToMenu(menuObj, FolderPath, HandlerFunctionName) {
Local i := 0, FolderList := "", FileList := "", PathList := "", iconIndex := 0
; 1) create folder menu entries
Loop Files FolderPath "\*", "D" ; loop throught folders (D = Directories)
FolderList .= (FolderList == "") ? A_LoopFileName : "`n" . A_LoopFileName ; create a list of all folders within this folder
FolderList := Sort(FolderList) ; sort this list alphabetically
Loop Parse FolderList, "`n" {
subMenuObj := Menu(), i++ ; create new submenu for folder
PathList .= AddFolderStructureToMenu(subMenuObj, FolderPath . "\" . A_LoopField, HandlerFunctionName) ; populate the submenu
menuObj.Add(A_LoopField, subMenuObj) ; add the menu entry for this folder
hIcon := DllCall("Shell32\ExtractAssociatedIcon", "Ptr", 0, "Str", FolderPath, "ShortP", &iconIndex, "Ptr")
menuObj.SetIcon(A_LoopField, "HICON:" . hIcon) ; add icon to menu entry
}
; 2) create file menu entries
Loop Files, FolderPath "\*", "F" ; loop throught files (F=Files)
FileList .= (FileList == "") ? A_LoopFileName : "`n" . A_LoopFileName ; create a list of all files within this folder
FileList := Sort(FileList) ; sort this list
Loop Parse, FileList, "`n" {
if ((A_LoopField == "") || InStr(A_LoopField, "~$") || InStr(A_LoopField, ".lnk")) ; ignore blanc file names or ones with ~$ in the name or links
continue
i++
filePath := FolderPath . "\" . A_LoopField
PathList .= filePath . "`n"
menuObj.Add(A_LoopField, %HandlerFunctionName%.Bind(filePath)) ; add the menu entry for this file
hIcon := DllCall("Shell32\ExtractAssociatedIcon", "Ptr", 0, "Str", filePath, "ShortP", &iconIndex, "Ptr") ; add icon to menu entry
menuObj.SetIcon(A_LoopField, "HICON:" . hIcon)
}
; 3) the folder has no containing files or folders - create disabled submenu "(Empty)"
if (i==0) {
handlerFunction := %HandlerFunctionName%.Bind("")
menuObj.Add("(Empty)", (*) => handlerFunction())
menuObj.Disable("(Empty)")
}
return PathList
}
Code: Select all
myMenu:= Menu()
allfilePaths:= AddFolderStructureToMenu(myMenu, PathToFolder, "theHandlerFunction")
myMenu.Show()
theHandlerFunction(filePath, *) {
; ... code here
MsgBox("File selected is" filePath)
}