-
Notifications
You must be signed in to change notification settings - Fork 25
/
combobox.go
122 lines (101 loc) · 2.39 KB
/
combobox.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
//+build windows
package wui
import (
"syscall"
"unsafe"
"github.com/gonutz/w32/v2"
)
func NewComboBox() *ComboBox {
return &ComboBox{selected: -1}
}
type ComboBox struct {
textControl
items []string
selected int
onChange func(newIndex int)
}
var _ Control = (*ComboBox)(nil)
func (c *ComboBox) closing() {
c.SelectedIndex()
}
func (*ComboBox) canFocus() bool {
return true
}
func (c *ComboBox) OnTabFocus() func() {
return c.onTabFocus
}
func (c *ComboBox) SetOnTabFocus(f func()) {
c.onTabFocus = f
}
func (*ComboBox) eatsTabs() bool {
return false
}
func (e *ComboBox) create(id int) {
e.textControl.create(
id,
w32.WS_EX_CLIENTEDGE,
"COMBOBOX",
w32.WS_TABSTOP|w32.CBS_DROPDOWNLIST,
)
for _, s := range e.items {
e.addItem(s)
}
e.SetSelectedIndex(e.selected)
}
func (e *ComboBox) AddItem(s string) {
e.items = append(e.items, s)
if e.handle != 0 {
e.addItem(s)
}
}
func (e *ComboBox) addItem(s string) {
ptr, _ := syscall.UTF16PtrFromString(s)
w32.SendMessage(e.handle, w32.CB_ADDSTRING, 0, uintptr(unsafe.Pointer(ptr)))
}
func (e *ComboBox) Clear() {
e.items = nil
if e.handle != 0 {
w32.SendMessage(e.handle, w32.CB_RESETCONTENT, 0, 0)
}
}
func (e *ComboBox) Items() []string {
return e.items
}
func (e *ComboBox) SetItems(items []string) {
e.items = items
if e.handle != 0 {
w32.SendMessage(e.handle, w32.CB_RESETCONTENT, 0, 0)
for _, s := range e.items {
e.addItem(s)
}
}
}
func (e *ComboBox) SelectedIndex() int {
if e.handle != 0 {
e.selected = int(w32.SendMessage(e.handle, w32.CB_GETCURSEL, 0, 0))
}
return e.selected
}
// SetSelectedIndex sets the current index. Set -1 to remove any selection and
// make the combo box empty. If you pass a value < -1 it will be set to -1
// instead. The index is not clamped to the number of items, you may set the
// index 10 where only 5 items are set. This lets you set the index and items at
// design time without one invalidating the other. At runtime though,
// SelectedIndex() will return -1 if you set an invalid index.
func (e *ComboBox) SetSelectedIndex(i int) {
if i < -1 {
i = -1
}
e.selected = i
if e.handle != 0 {
w32.SendMessage(e.handle, w32.CB_SETCURSEL, uintptr(i), 0)
}
}
func (e *ComboBox) SetOnChange(f func(newIndex int)) {
e.onChange = f
}
func (e *ComboBox) handleNotification(cmd uintptr) {
if cmd == w32.CBN_SELCHANGE && e.onChange != nil {
e.onChange(e.SelectedIndex())
}
}