Re: Event to return value

Tech-Archive recommends: Fix windows errors by optimizing your registry

From: Ken Kolda (ken.kolda_at_elliemae-nospamplease.com)
Date: 07/09/04


Date: Fri, 9 Jul 2004 10:51:42 -0700

See comments inline...

> private void textBox1_KeyPress(object sender,
> System.Windows.Forms.KeyPressEventArgs e)
>
> {
>
> e.Handled = true;
>
> ((TextBox)sender).Text += e.KeyChar.ToString().ToUpper();
>
> }

The event handler code above isn't sufficient because you don't know that
when the user pressed the key that the cursor is at the end of the textbox.
You'll need to use the SelectionStart and SelectionLength properties to
ensure that your character is placed in the correct location (and whatever
text was selected is removed), e.g.

public static void uCaseReturn(object sender,
System.Windows.Forms.KeyPressEventArgs e)
{
    if (!Char.IsControl(e.KeyChar))
    {
        TextBox tb = (TextBox) sender;
        int charPosition = tb.SelectionStart;

        // Build the new text for the box by replacing the selected text
with the character (in uppercase)
        tb.Text = tb.Text.Substring(0, charPosition) +
            Char.ToUpper(e.KeyChar) +
            tb.Text.Substring(tb.SelectionStart + tb.SelectionLength);

        // Place the cursor in the correct location
        tb.SelectionLength = 0;
        tb.SelectionStart = charPosition;

        // Mark the keystroke as being handled
        e.Handled = true;
    }
}

Ken



Relevant Pages

  • Re: C# Extended Text Editor
    ... The text box has a SelectionStart property, if no text is selected it will ... to the length of the tag, or auto move the selectionstart to just past the ... cursor to either side of the field, never let him land right in a tag. ... but is there a similar method for the textbox control? ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Cursor location in Textbox
    ... SelectionStart is used to return the position of the cursor and will work ... When you get focus back on the textbox again after performing your ... > I want to get the cursor location in a textbox. ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Event to return value
    ... >> private void textBox1_KeyPress(object sender, ... > You'll need to use the SelectionStart and SelectionLength properties to ... > ensure that your character is placed in the correct location (and whatever ... > public static void uCaseReturn(object sender, ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: Caret Position in Textbox Control
    ... The position of the caret is always at SelectionStart. ... the caret in the character array in the TextBox. ...
    (microsoft.public.dotnet.framework.windowsforms.controls)
  • richtextbox color text
    ... I am loading a file into an RTB for editing. ... I know you can use selectionstart, ... cursor is, then selection start and length of 1 always? ...
    (microsoft.public.dotnet.languages.vb)