Alex Rivera | Logout

Winforms Textbox - Using Ctrl-Backspace to Delete Whole Word

Asked 2009-07-14T10:47:19.893
36

I have a Winforms dialog that contains among other controls a TextBox that allows a single line of input. I would like to allow the user to be able to press Ctrl-Backspace to delete an entire word. This is not the default behaviour with the out-of-the-box TextBox; I get a rectangle character, rather than having the word deleted.

I have confirmed the ShortcutsEnabled property is set to True.

I did find that I can use a RichTextBox rather than a TextBox to get the behaviour I want. The problem with this is that the apperance of the RichTextBox (border in particular) is different from that of the TextBox, and I don't need or want the ability to mark up text.

So my question is how to best handle this situation? Is there some property on the TextBox that I am missing? Or is it best to use the RichTextBox, update the appearance so it is consistent, and disable markup of the text?

I am relatively happy to write the code to handle the KeyDown and KeyPress events explicity if there is no better way, but thought it was worth checking first.

Edit
Report

2 Answers

6

I'm not sure it is possible without a custom KeyDown or KeyPress event, the following code works though:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if ((e.KeyCode == Keys.Back) && e.Control)
    {
        e.SuppressKeyPress = true;
        int selStart = textBox1.SelectionStart;
        while (selStart > 0 && textBox1.Text.Substring(selStart - 1, 1) == " ")
        {
            selStart--;
        }
        int prevSpacePos = -1;
        if (selStart != 0)
        {
            prevSpacePos = textBox1.Text.LastIndexOf(' ', selStart - 1);
        }
        textBox1.Select(prevSpacePos + 1, textBox1.SelectionStart - prevSpacePos - 1);
        textBox1.SelectedText = "";
    }
}
answered 2009-07-14T12:34:20.540
3

This is the way yo go :)

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    //if ctrl+bcksp
    if (e.KeyChar == 127)
    {
        //if not last word
        if (textBox1.Text.Split (' ').Count() > 1)
        {
            //remoce last word form list and put it back together (gotta love lambda)
            textBox1.Text = textBox1.Text.Split (' ').Take (textBox1.Text.Split (' ').Count() - 1).Aggregate ((a,b) => a + " " + b);
            //set selection at the end
            textBox1.SelectionStart = textBox1.Text.Length;
        }
        else if (textBox1.Text.Split (' ').Count() == 1)
        {
            textBox1.Text = "";
        }
    }
}
answered 2009-07-14T11:51:56.597

Your Answer