Add File or URL AutoCompletion to TextBoxes and ComboBoxes

Demonstrates how to add File System and/or URL AutoCompletion to a TextBox or Combo Box, using the same code used for the System Common Dialog file name, Start->Run dialog box and IE Address bar. Note that IE5 or above is required to use this function.

Start a new project in VB and add a Module. Then add this code to the Module:

Option Explicit

Public Enum SHAutoCompleteFlags
   ' // This includes the File System as well as the rest of the shell 
   ' (Desktop\My Computer\Control Panel\)
   ' // URLs in the User's History
   ' // URLs in the User's Recently Used list.
   ' // Use the tab to move thru the autocomplete possibilities 
   ' instead of to the next dialog/window control.
   ' // This includes the File System 
   SHACF_FILESYS_ONLY = &H10                     

'#if (_WIN32_IE >= = &H0600)
   ' // Same as SHACF_FILESYS_ONLY except it only includes directories, 
   ' UNC servers, and UNC server shares. 
   SHACF_FILESYS_DIRS = &H20                     
'#End If ' // (_WIN32_IE >= = &H0600)
   ' // Ignore the registry default and force the feature on.
   ' // Ignore the registry default and force the feature off.
   ' // Ignore the registry default and force the feature on. 
   ' (Also know as AutoComplete)
    ' // Ignore the registry default and force the feature off. 
    ' (Also know as AutoComplete)
End Enum

Private Declare Function SHAutoComplete Lib "shlwapi.dll" ( _
   ByVal hwndEdit As Long, ByVal dwFlags As Long) As Long
Private Declare Function FindWindowEx Lib "user32" Alias "FindWindowExA" _
   (ByVal hwndParent As Long, ByVal hwndChildAfter As Long, ByVal lpszClass As String, _
   ByVal lpszWindow As String) As Long

Private Const S_OK = 0

Public Function AutoComplete( _
      ByVal hWnd As Long, _
      ByVal eFlags As SHAutoCompleteFlags _
Dim lR As Long
   lR = SHAutoComplete(hWnd, eFlags)
   AutoComplete = (lR <> S_OK)
End Function
Public Function GetComboBoxEdithWnd(ByVal hWnd As Long) As Long
   GetComboBoxEdithWnd = FindWindowEx(hWnd, 0, "EDIT", vbNullString)
End Function

To test the function, add a TextBox and a ComboBox to the Project's form. Name the TextBox "txtTest" and the ComboBox "cboTest". Then add this code to the project's form:

Private Sub Form_Load()
   AutoComplete txtTest.hWnd, SHACF_FILESYS_ONLY
   AutoComplete GetComboBoxEdithWnd(cboTest.hWnd), SHACF_FILESYS_ONLY
End Sub

Run the project. When you start typing a file name into either of the controls, you will see that the AutoComplete drop down displays, and you can pick the nearest matching file.