Date: 02-16-2022
Return to Index
created by gbSnippets
Pierre Bellisle
'Create an new combobox item by typing in text and hitting "Enter"
'The new item will be on the top of the list and any duplicate will be removed
'Upper-lower case insensitive. Number of items is limited by %ComboItemMax
'Credit : Pierre Bellisle
'Compilable Example: (Jose Includes)
#Compiler PBWin 9, PBWin 10
#Compile EXE
#Dim All
%Unicode=1
#Include "Win32Api.inc"
Global hDlg AS DWord
%COMBOBOX01 = 101
%COMBOITEMMAX = 5
Function PBMAIN()
DIALOG NEW %HWND_DESKTOP, "Combobox, add item with enter", , , 230, 60, %WS_CAPTION OR _
%WS_MINIMIZEBOX OR %WS_MAXIMIZEBOX OR %WS_SYSMENU OR %WS_THICKFRAME, 0 TO hDlg
SetClassLong(hDlg, %GCL_HICON, LoadIcon(ByVal %NULL, ByVal %IDI_INFORMATION)) 'Icon from Windows
CONTROL ADD COMBOBOX, hDlg, %COMBOBOX01, , 50, 20, 140, 250, %CBS_AUTOHSCROLL OR _
%CBS_DROPDOWN OR %WS_TABSTOP OR %WS_VSCROLL, %WS_EX_CLIENTEDGE OR %WS_EX_LEFT
DIALOG SHOW MODAL hDlg CALL DlgProc
End Function
CallBack Function DlgProc
SELECT CASE CBMSG
CASE %WM_COMMAND
SELECT CASE LOWRD(CBWPARAM)
CASE %IDOK 'Enter key
IF GetParent(GetFocus()) = GetDlgItem(hDlg, %COMBOBOX01) THEN 'On the combo edit part
ComboboxSet(%COMBOBOX01)
END IF
END SELECT
END SELECT
End Function
Sub ComboboxSet(ComboId AS DWord)
Local sNewItem As String
Local sBuffer As String
Local ComboItemCount AS DWord
Local hCombobox AS DWord
Local Looper As Long
hCombobox = GetDlgItem(hDlg, ComboId) 'Get combo handle
sNewItem = NUL$(SendMessage(hCombobox, %WM_GETTEXTLENGTH, 0, 0)) 'Create a buffer to get edit part of combo
SendMessage(hCombobox, %WM_GETTEXT, 1 + LEN(sNewItem), STRPTR(sNewItem)) 'Get text from edit part of combo
IF LEN(sNewItem) THEN 'Check if item is not nul
SendMessage(hCombobox, %CB_INSERTSTRING, 0, STRPTR(sNewItem)) 'Insert item at top
ComboItemCount = SendMessage(hCombobox, %CB_GETCOUNT, 0, 0) 'Get combo item count
IF ComboItemCount > 1 THEN
FOR Looper = 1 TO ComboItemCount - 1 'Start with second item, item are zero based
sBuffer = NUL$(SendMessage(hCombobox, %CB_GETLBTEXTLEN, Looper, 0) + 1) 'Create a buffer
SendMessage(hCombobox, %CB_GETLBTEXT, Looper, STRPTR(sBuffer)) 'Get text item in buffer
sBuffer = LEFT$(sBuffer, LEN(sBuffer) - 1) 'Remove last $NULL
IF UCASE$(sBuffer) = UCASE$(sNewItem) THEN 'Is new item already exist, any upper-lower case
SendMessage(hCombobox, %CB_DELETESTRING, Looper, 0) 'Yes, delete it
EXIT FOR 'We are done
END IF
NEXT
IF ComboItemCount > %COMBOITEMMAX THEN 'Limit the maximum items in combo
FOR Looper = %COMBOITEMMAX - 1 TO ComboItemCount - 1
SendMessage(hCombobox, %CB_DELETESTRING, %COMBOITEMMAX, 0) 'Delete surplus items
NEXT
END IF
END IF
END IF
SendMessage(hCombobox, %CB_SETCURSEL, 0, 0) 'Highlight text in the edit control
End Sub
'gbs_00778
http://www.garybeene.com/sw/gbsnippets.htm