Click here to Skip to main content
15,881,789 members
Articles / Desktop Programming / MFC
Article

Implementing an autocompleting Combobox

Rate me:
Please Sign up or sign in to vote.
4.95/5 (43 votes)
18 Oct 2000CPOL 304.5K   4.8K   100   29
A combobox that autocompletes as you type

ComboCompletion.gif

Introduction

I had a need for a combobox that would auto-complete, very much like the URL edit box in the toolbar of Netscape Navigator. It was actually surprisingly simple since the base CComboBox is so rich in functionality.

The basic idea is that every time the text in the edit box changes, check to see if there is any text in the drop down list that is prefixed by this edit box text. Handle the CBN_EDITUPDATE message to get the text change notifications, and use GetWindowText() to get the text. CComboBox::SelectString will look for a string in the list which is prefixed by the given string, and select it into the edit box. I then select the portion of text that was added to the users typed text so that they can continue typing and have the additions ignored if they wish. That takes care of 90% of the work.

The only trick is in handling backspaces and deletes. When a user hits delete, the text is changed, and the auto-completion routine will try to restore that text back again. Just check in PreTranslateMessage for a KEY_DOWN message with a virtual key of VK_DELETE or VK_BACK, and temporarily disable the auto-complete mechanism for those key strokes.

Source code

#if !defined(AFX_ComboCompletion_H__115F422E_5CD5_11D1_ABBA_00A02__INCLUDED_)
#define AFX_ComboCompletion_H__115F422E_5CD5_11D1_ABBA_00A02__INCLUDED_

#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000

// ComboCompletion.h : header file
//
// Copyright (c) Chris Maunder 1997.
// Please feel free to use and distribute.


/////////////////////////////////////////////////////////////////////////////
// CComboCompletion window

class CComboCompletion : public CComboBox
{
// Construction
public:
    CComboCompletion();

// Attributes
public:

// Operations
public:

// Overrides
    // ClassWizard generated virtual function overrides
    //{{AFX_VIRTUAL(CComboCompletion)
    public:
    virtual BOOL PreTranslateMessage(MSG* pMsg);
    //}}AFX_VIRTUAL

// Implementation
public:
    virtual ~CComboCompletion();

    BOOL m_bAutoComplete;

    // Generated message map functions
protected:
    //{{AFX_MSG(CComboCompletion)
    afx_msg void OnEditUpdate();
    //}}AFX_MSG

    DECLARE_MESSAGE_MAP()
};

/////////////////////////////////////////////////////////////////////////////

//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately 
// before the previous line.

#endif 



// ComboCompletion.cpp : implementation file
//
// Copyright (c) Chris Maunder 1997.
// Please feel free to use and distribute.

#include "stdafx.h"
#include "ComboCompletion.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CComboCompletion

CComboCompletion::CComboCompletion()
{
    m_bAutoComplete = TRUE;
}

CComboCompletion::~CComboCompletion()
{
}


BEGIN_MESSAGE_MAP(CComboCompletion, CComboBox)
    //{{AFX_MSG_MAP(CComboCompletion)
    ON_CONTROL_REFLECT(CBN_EDITUPDATE, OnEditUpdate)
    //}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CComboCompletion message handlers

BOOL CComboCompletion::PreTranslateMessage(MSG* pMsg)
{
    // Need to check for backspace/delete. These will modify the text in
    // the edit box, causing the auto complete to just add back the text
    // the user has just tried to delete. 

    if (pMsg->message == WM_KEYDOWN)
    {
        m_bAutoComplete = TRUE;

        int nVirtKey = (int) pMsg->wParam;
        if (nVirtKey == VK_DELETE || nVirtKey == VK_BACK)
            m_bAutoComplete = FALSE;
    }

    return CComboBox::PreTranslateMessage(pMsg);
}

void CComboCompletion::OnEditUpdate() 
{
  // if we are not to auto update the text, get outta here
  if (!m_bAutoComplete) 
      return;

  // Get the text in the edit box
  CString str;
  GetWindowText(str);
  int nLength = str.GetLength();
  
  // Currently selected range
  DWORD dwCurSel = GetEditSel();
  WORD dStart = LOWORD(dwCurSel);
  WORD dEnd   = HIWORD(dwCurSel);

  // Search for, and select in, and string in the combo box that is prefixed
  // by the text in the edit box
  if (SelectString(-1, str) == CB_ERR)
  {
      SetWindowText(str);            // No text selected, so restore what 
                                     // was there before
      if (dwCurSel != CB_ERR)
        SetEditSel(dStart, dEnd);    //restore cursor postion
  }

  // Set the text selection as the additional text that we have added
  if (dEnd < nLength && dwCurSel != CB_ERR)
      SetEditSel(dStart, dEnd);
  else
      SetEditSel(nLength, -1);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Founder CodeProject
Canada Canada
Chris Maunder is the co-founder of CodeProject and ContentLab.com, and has been a prominent figure in the software development community for nearly 30 years. Hailing from Australia, Chris has a background in Mathematics, Astrophysics, Environmental Engineering and Defence Research. His programming endeavours span everything from FORTRAN on Super Computers, C++/MFC on Windows, through to to high-load .NET web applications and Python AI applications on everything from macOS to a Raspberry Pi. Chris is a full-stack developer who is as comfortable with SQL as he is with CSS.

In the late 1990s, he and his business partner David Cunningham recognized the need for a platform that would facilitate knowledge-sharing among developers, leading to the establishment of CodeProject.com in 1999. Chris's expertise in programming and his passion for fostering a collaborative environment have played a pivotal role in the success of CodeProject.com. Over the years, the website has grown into a vibrant community where programmers worldwide can connect, exchange ideas, and find solutions to coding challenges. Chris is a prolific contributor to the developer community through his articles and tutorials, and his latest passion project, CodeProject.AI.

In addition to his work with CodeProject.com, Chris co-founded ContentLab and DeveloperMedia, two projects focussed on helping companies make their Software Projects a success. Chris's roles included Product Development, Content Creation, Client Satisfaction and Systems Automation.

Comments and Discussions

 
QuestionI have a doubt, can you help me to solve it Pin
vicky_tm19-Jul-18 3:38
vicky_tm19-Jul-18 3:38 
GeneralCComboCOmpletion in two dialogs Pin
Anu_Bala27-Jul-08 19:25
Anu_Bala27-Jul-08 19:25 
GeneralLittle Bug Pin
Christopher Stratmann22-Aug-06 23:56
Christopher Stratmann22-Aug-06 23:56 
GeneralRe: Little Bug Pin
ellolazo28-Aug-06 9:27
ellolazo28-Aug-06 9:27 
GeneralRe: Little Bug Pin
ellolazo31-Aug-06 5:34
ellolazo31-Aug-06 5:34 
GeneralEnter in combobox and default button Pin
ellolazo12-Jun-06 6:57
ellolazo12-Jun-06 6:57 
GeneralHelp..Enter key Pin
G.Inbakumar20-Feb-06 5:29
G.Inbakumar20-Feb-06 5:29 
QuestionGreat Works,Can you complete it with C#? Pin
Alenty8-Jun-05 14:59
Alenty8-Jun-05 14:59 
AnswerRe: Great Works,Can you complete it with C#? Pin
bobishkindaguy27-Aug-05 11:51
bobishkindaguy27-Aug-05 11:51 
GeneralSuggestion Pin
starschen20-Apr-05 17:48
sussstarschen20-Apr-05 17:48 
GeneralBackspace and Enter key Pin
rlaley28-Oct-04 1:54
rlaley28-Oct-04 1:54 
GeneralRe: Backspace and Enter key Pin
rlaley31-Oct-04 16:21
rlaley31-Oct-04 16:21 
GeneralRe: Backspace and Enter key Pin
RedFox20-Feb-05 4:23
RedFox20-Feb-05 4:23 
GeneralRe: Backspace and Enter key Pin
rlaley20-Feb-05 17:20
rlaley20-Feb-05 17:20 
GeneralCapturing a right-click on the combo box Pin
Flic13-Feb-03 17:07
Flic13-Feb-03 17:07 
GeneralRe: Capturing a right-click on the combo box Pin
abdulsoni18-Dec-03 20:29
abdulsoni18-Dec-03 20:29 
GeneralView options Pin
9-May-02 4:16
suss9-May-02 4:16 
GeneralSimple-type ComboBox Highlight Pin
6-Jan-02 13:49
suss6-Jan-02 13:49 
GeneralGetCurSel() for the CComboBox is returns 2 different values on consecutive calls Pin
Ed Mitchell3-Oct-01 3:23
Ed Mitchell3-Oct-01 3:23 
GeneralCBN_SELENDOK and CBN_SELCHANGE Pin
Michael Martin13-Sep-01 3:25
professionalMichael Martin13-Sep-01 3:25 
GeneralRe: CBN_SELENDOK and CBN_SELCHANGE Pin
Carlos Antollini13-Sep-01 3:53
Carlos Antollini13-Sep-01 3:53 
GeneralGetCurSel() doesn't return the selected index. Pin
2-Aug-01 20:27
suss2-Aug-01 20:27 
GeneralRe: GetCurSel() doesn't return the selected index. Pin
Kyle Poole17-May-03 7:03
Kyle Poole17-May-03 7:03 
GeneralRe: GetCurSel() doesn't return the selected index. Pin
M. Wohlers3-Jan-05 1:43
M. Wohlers3-Jan-05 1:43 
GeneralUsing your Class in a non Dialog based app for example in a SDI/MDI embedded in toolbar & Rebar similar to IE 5 Pin
25-Jan-01 3:03
suss25-Jan-01 3:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.