用C++ Builder 实现类似ie地址栏的ComboBox

来源:互联网 发布:网管协议 snmp端口 编辑:程序博客网 时间:2024/06/11 00:43

大家一定对ie浏览器的地址栏很熟悉,几乎没有没用过的人,当你输入一串字符时,下拉列表会列出所有历史记录中存放的地址前几位字符和输入字符相符的条目。

我们在设计程序也需要这种技术以方便用户输入,它是怎么实现的呢?

下面我就说说我用CBuilder实现这种效果的方法:

首先新建一个应用程序,在窗体上ComboBox,名称设为:ComboBox1

在头文件中声明一个stringlist

TStringList *MyDropDownList;

在应用程序初始化部门将所有列表数据存入MyDropDownList;

在ComboBox1的KeyPress中加入以下代码:

nt i, iInputLength, iSelStartRestore, iSelLengthRestore;
AnsiString strInput;
TStringList *TempList;

strInput= ComboBox1->Text;


  if (Key == VK_ESCAPE)
  {
    Key = 0x0; // No more beeping after pressing Escape.
  }

  if (Key == VK_RETURN)
   {
       Key = 0x0;
    if (ComboBox1->Items->IndexOf(strInput) == -1) ComboBox1->Items->Add(strInput);
    ComboBox1->DroppedDown = False;

    ComboBox1->SelStart = ComboBox1->Text.Length();

   }
  else
   {
   iSelStartRestore = ComboBox1->SelStart;
    iSelLengthRestore = ComboBox1->SelLength;
    if (Key == VK_BACK)
    {
      // Handle backspace:
      if ((ComboBox1->SelLength == 0) && (ComboBox1->SelStart > 0))
      {
        ComboBox1->SelStart = ComboBox1->SelStart - 1;
        ComboBox1->SelLength = ComboBox1->SelLength + 1;
      }
    }
      strInput.Delete(ComboBox1->SelStart + 1, ComboBox1->SelLength);

    if (Key != VK_BACK)
           {
           strInput.Insert(Key, ComboBox1->SelStart + 1);
           }
    iInputLength = strInput.Length();
    ComboBox1->Items->Clear();
    if (iInputLength > 0)
    {

      TempList = new TStringList;
      try
         {
             for ( i= 0; i<MyDropDownList->Count - 1;i++)
                 {
                    if ((MyDropDownList->Strings[i].SubString(1, iInputLength)).UpperCase() ==
                           strInput.UpperCase())
                      TempList->Add(MyDropDownList->Strings[i]);

                  }
        if (TempList->Count > 0)
        {
          for (i = 0 ;i<7;i++) ComboBox1->Items->Add("");
           ComboBox1->DropDownCount = 8;
          ComboBox1->DroppedDown = True;
          ComboBox1->Items->Clear();
          ComboBox1->Items = TempList;
         }
        else ComboBox1->DroppedDown = False;
       }

        __finally
       {
        TempList->Free();
       }
      }
      else

            ComboBox1->DroppedDown = False;
    // Restore the position of the carrot and the selected text:
    ComboBox1->SelStart = iSelStartRestore;
    ComboBox1->SelLength= iSelLengthRestore;

}

在C++ Builder win2000下实现,其他应该也可以。

 

 

 

 

 

原创粉丝点击