(1)新建一个基于对话框的应用程序
(2)在工程中添加新类AutoComplete,基类为CComboBox.
为该类添加一个变量public: bool m_bAutoComplete;
(3)在对话框上添加组合框控件,添加成员变量m_sercmb,type为AutoComplete
在对话框的头文件 2_068Dlg.h添加代码#include "AutoComplete.h"
(4)在对话框OnInitDialog()方法中添加代码:
BOOL CMy2_068Dlg::OnInitDialog()
{
CDialog::OnInitDialog();
……
// TODO: Add extra initialization here
m_sercmb.AddString("Monday");
m_sercmb.AddString("Tuesday");
m_sercmb.AddString("Wednesday");
m_sercmb.AddString("Thursday");
m_sercmb.AddString("Friday");
m_sercmb.AddString("Saturday");
m_sercmb.AddString("Sunday");
return TRUE; // return TRUE unless you set the focus to a control
}
(5)在新类AutoComplete中添加=CBN_EDITUPDATE消息的实现函数
void AutoComplete::OnEditupdate()
{
if(!m_bAutoComplete) return;
CString str;
GetWindowText(str); //获得组合框的编辑框文本
int nLength=str.GetLength(); //获得文本长度
DWORD dwCurSel=GetEditSel(); //获得文本的起始位置
DWORD dStart =LOWORD(dwCurSel);
DWORD dEnd =HIWORD(dwCurSel);
if(SelectString(-1,str)==CB_ERR) //查找字符
{
SetWindowText(str); //设置显示字符串
if(dwCurSel!=CB_ERR)
SetEditSel(dStart,dEnd); //设置编辑框部分选中的字符串
}
GetWindowText(str);
if(dEnd < nLength && dwCurSel!=CB_ERR)
SetEditSel(dStart,dEnd);
else
SetEditSel(nLength,-1);
}
(6)在新类AutoComplete中添加PreTranslateMessage消息的实现函数
BOOL AutoComplete::PreTranslateMessage(MSG* pMsg)
{
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);
}