
;~ http://www.autohotkey.com/board/topic/2391-listbox-with-incremental-search/
Gui Add, Edit, w300 h30 vsearchedString gIncrementalSearch
Gui Add, ListBox, vchoice gListBoxClick w300 h250 hscroll vscroll
Gui Add, Button, gListBoxClick Default, OK
Gosub FillListBox
Gui Show
Return
IncrementalSearch:
Gui Submit, NoHide
len := StrLen(searchedString)
itemNb := 1
Loop Parse, listContent, |
{
StringLeft part, A_LoopField, len
;~ Tooltip %part% (%A_LoopField%)
;~ Sleep 500
If (part = searchedString)
{
itemNb := A_Index
Break
}
}
Tooltip %searchedString% (%itemNb%)
SetTimer HideTooltip, 1000
GuiControl Choose, choice, %itemNb%
Return
HideTooltip:
SetTimer HideTooltip, Off
Tooltip
Return
ListBoxClick:
Gui Submit, NoHide
MsgBox Choice: %choice%
Return
GuiClose:
GuiEscape:
ExitApp
FillListBox:
listContent =
( Join|
car|bicyle|train|plane|road|railway station|track|airport|control tower|wheel
red|green|pink|blue|grey|silver|black|yellow|brown|white
hair|nose|eye|ear|face|mustache|neck|collar|arm|hand|forearm|forehead
finger|thumb|palm|back|stomach|leg|thigh|foot|toe
shoe|sock|stocking|trousers|jumpsuit|skirt|blouse|dress|shirt|tie|necklace|earring
Sun|Moon|Mercure|Venus|Earth|Mars|Jupiter|Saturn|Neptun|Pluto
Africa|America|Antarctica|Asia|Australia|Europe
Canada|USA|Mexico|Guatemala|Honduras|Cuba
Gui Add|Gui Show|Gui Submit|Gui Hide|Gui Destroy
)
GuiControl, , choice, %listContent%
Return
说明
这个示例演示了带增量检索(incremental search)功能的 ListBox 列表框:界面上方是一个编辑框(Edit),下方是一个列表框(ListBox),当你在编辑框中输入文字时,脚本会根据输入实时高亮/选中列表中匹配的项,实现类似搜索引擎的即时过滤效果。它的核心原理并不复杂:在 IncrementalSearch 子程序里取得编辑框当前输入,用 StrLen 得到长度,然后Loop Parse逐项解析列表内容,用 StringLeft 取每项开头与输入比较,命中后通过 GuiControl Choose 选中对应项,并用 Tooltip 显示当前命中位置。
适用场景:需要在一大串候选项中快速定位数据的工具(比如城市选择、单词表、设备列表等),比从头滚动查找高效得多。
几点补充:
- 该脚本为 AutoHotkey v1 写法;在 v2 中对应命令改为函数式,例如
StrLen()、GuiControl()、StringLeft()用SubStr()取代,GUI 用MyGui := Gui()对象化创建。 - 列表数据用管道符
|分隔,通过GuiControl一次性填入列表框。 - 若输入在列表中不存在,可不做处理或给出提示,避免误选中。

