# Friday, June 18, 2004

Automatic Capitalisation Of Words In A Text Box

A question arose recently on the newsgroup of how to automatically capitalise the first letter of a word in a text box, e.g. by activating the shift key on the soft keyboard. Since there is no API for the SIP to do this the workaround is to simulate a mouse click over the position of the Shift key in the soft keyboard.

An alternative method is to handle the TextChanged event on the TextBox and add some logic to capitalise words as the text is entered. The advantage here is that it is not dependent on a specific SIP being in use:-

private void textBox1_TextChanged(object sender, System.EventArgs e)

{

  //start with true as the first character should always be upper case

  bool makeUpper = true;

  //get the current text as a char array

  char[] oldText = textBox1.Text.ToCharArray();

  //create a new char array the same size for the new text

  char[] newText = new char[oldText.Length];

  //for each char

  for(int iChar = 0; iChar < oldText.Length; iChar++)

  {

    if(makeUpper)

    {

      //make the character upper-case and reset the flag

      newText[iChar] = Char.ToUpper(oldText[iChar]);

      makeUpper = false;

    }

    else

    {

      //copy the character as-is

      newText[iChar] = oldText[iChar];

    }

    //if it's a space the next character should be upper-case

    if(oldText[iChar] == ' ')

    {

      makeUpper = true;

    }

  }

  //assign the new value

  textBox1.Text = new String(newText);

  //position the cursor at the end of the text

  textBox1.SelectionStart = textBox1.Text.Length;

}

#    Comments [2] |