SelLength (C++)

From RAD Studio Code Examples
Jump to: navigation, search

Description

The following example shows how to complete partial strings typed into a combo box. The code represents the OnKeyPress event handler of the combo box, which performs most of the default keystroke handling before finding a matching list item and updating the text. Note: This OnKeyPress event handler does not deal with the case when you press the Delete key. That case must be caught in the OnKeyDown event handler instead.

Code

void __fastcall TForm1::ComboBox1KeyPress(TObject *Sender, char &Key)
{
  // First, process the keystroke to obtain the current string.
  // This code requires all items in the list to be uppercase.
  if (Key >= 'a' && Key <= 'z')
    Key -= 32; // Force Uppercase only!
  TComboBox *pCB = dynamic_cast<TComboBox *>(Sender);
  String TmpStr;
  bool BackSpace = (Key == (char)VK_BACK);
  if (BackSpace && pCB->SelLength)
    TmpStr = pCB->Text.SubString(1,pCB->SelStart)+
             pCB->Text.SubString(pCB->SelLength+pCB->SelStart+1,255);
  else if (BackSpace) // SelLength == 0
    TmpStr = pCB->Text.SubString(1,pCB->SelStart-1)+
             pCB->Text.SubString(pCB->SelStart+1,255);
  else //Key is a visible character.
    TmpStr = pCB->Text.SubString(1,pCB->SelStart)+ Key +
             pCB->Text.SubString(pCB->SelLength+pCB->SelStart+1,255);
  if (TmpStr.IsEmpty())
    return;
  // Set SelSt to the current insertion point.
  int SelSt = pCB->SelStart;
  if (BackSpace && SelSt > 0)
    SelSt--;
  else if (!BackSpace)
    SelSt++;
  Key = 0; // Indicate that the key was handled.
  if (SelSt == 0)
  {
	pCB->Text = L"";
    return;
  }
  // Now that TmpStr is the currently typed string, see if you can locate a match.
  bool Found = false;
  for (int i = 1; i < pCB->Items->Count; i++)
    if (TmpStr == pCB->Items->Strings[i-1].SubString(1,TmpStr.Length()))
    {
	  pCB->Text = pCB->Items->Strings[i-1]; // Update to the match that was found.
      pCB->ItemIndex = i-1;
      Found = true;
      break;
    }
  if (Found) // Select the untyped end of the string.
  {
	pCB->SelStart = SelSt;
	pCB->SelLength = pCB->Text.Length() - SelSt;
  }
  else Beep();
}

TStringList *CharSetList;

void __fastcall TForm1::AddCharacterSet(String S)
{
  CharSetList->Add(S);
}

#include <memory>       //For STL auto_ptr class

__fastcall TForm1::TForm1(TComponent* Owner)
  : TForm(Owner)
{
  static std::auto_ptr<TStringList> _CharSetListCleaner(CharSetList = new TStringList);
  GetCharsetValues(AddCharacterSet);
  CharSetList->Sort();
  ComboBox1->Items = CharSetList;
}

Uses