#include <GuiConstantsEx.au3>
#include <GuiTreeView.au3>
#include <WindowsConstants.au3>
$GUI = GUICreate("树视图(TreeView) UDF 函数演示", 400, 300)
$hTreeView = GUICtrlCreateTreeView(2, 2, 396, 268, BitOR($TVS_EDITLABELS, $TVS_HASBUTTONS, $TVS_HASLINES, $TVS_LINESATROOT))
For $x = 1 To 3
$hItem = GUICtrlCreateTreeViewItem(StringFormat("[%02d] 主项", $x), $hTreeView)
For $y = 1 To Random(2, 10, 1)
GUICtrlCreateTreeViewItem(StringFormat("[%02d] 子项", $y), $hItem)
Next
Next
$RightMenu = GUICtrlCreateContextMenu($hTreeView)
$AddBtnP = GUICtrlCreateMenuItem("增加根项目", $RightMenu)
GUICtrlCreateMenuItem("", $RightMenu)
$AddBtnC = GUICtrlCreateMenuItem("增加子项目", $RightMenu)
GUICtrlCreateMenuItem("", $RightMenu)
$DelBtn = GUICtrlCreateMenuItem("删除项目", $RightMenu)
GUICtrlCreateMenuItem("", $RightMenu)
$RenameBtn = GUICtrlCreateMenuItem("重命名", $RightMenu)
GUISetState()
; 循环到用户退出
While 1
$Msg = GUIGetMsg()
Switch $Msg
Case $GUI_EVENT_CLOSE
Exit
Case $AddBtnP, $AddBtnC
$SelectItem = _GUICtrlTreeView_GetSelection($hTreeView)
If $SelectItem = 0 Or $Msg = $AddBtnP Then
$NewItem = _GUICtrlTreeView_Add($hTreeView, 0, "新项目")
Else
_GUICtrlTreeView_Expand($hTreeView, $SelectItem)
$NewItem = _GUICtrlTreeView_AddChild($hTreeView, $SelectItem, "新项目")
EndIf
$EditHWND = _GUICtrlTreeView_EditText($hTreeView, $NewItem)
_UpItemText($EditHWND, $NewItem)
Case $DelBtn
$SelectItem = _GUICtrlTreeView_GetSelection($hTreeView)
$ItemText = _GUICtrlTreeView_GetText($hTreeView, $SelectItem)
If _GUICtrlTreeView_GetChildren($hTreeView, $SelectItem) Then
$Text = '确定要删除 "' & $ItemText & '" 项目及其全部子项吗?'
Else
$Text = '确定要删除 "' & $ItemText & '" 项目吗?'
EndIf
If MsgBox(32+1, "请确认", $Text) = 1 Then
_GUICtrlTreeView_Delete($hTreeView, $SelectItem)
EndIf
Case $RenameBtn
$SelectItem = _GUICtrlTreeView_GetSelection($hTreeView)
$EditHWND = _GUICtrlTreeView_EditText($hTreeView, $SelectItem)
_UpItemText($EditHWND, $SelectItem)
EndSwitch
WEnd
Func _UpItemText($EditHWND, $SelectItem)
$sText = ""
While WinExists($EditHWND)
$sText = WinGetTitle($EditHWND)
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
Exit
Case -8 ;如果鼠标释放且鼠标光标位置没有控件,说明点击在窗口空白区域上
$Pos = GUIGetCursorInfo($GUI)
If $Pos[4] = 0 Then _GUICtrlTreeView_EndEdit($hTreeView)
EndSwitch
WEnd
_GUICtrlTreeView_SetText($hTreeView, $SelectItem, $sText)
_GUICtrlTreeView_SetFocused($hTreeView, $SelectItem)
EndFunc