jay_t55
jay_t55

Reputation: 11662

Is this Inconsistent behavior between TextBox controls

I just made a simple note-taking application and I have noticed many times that TextBox controls in Windows Forms appications do not support backspacing by a Tab. However I have noticed that "TextBox" controls in websites do (well most of them) and also TextBox controls in WPF applications also support backspacing by a Tab.

If you're unsure of what I mean by this, type a few words separated by spaces, then, hold down the Ctrl key and tap the Backspace key. You'll notice that it doesn't just backspace by one, but by a full Tab space.

Why is this behavior so inconsistent?

Is it because only newer versions of the Text input controls support this behavior? Does it have something to do with my keyboard settings?

The question: How should I best implement/force a Back-Tab-space in my Windows Forms application's TextBox Control, while also respecting the user's Tab spacing settings for Windows (i.e. The number of spaces the Tab key will produce when tapped)?

Note: In the controls that do not support this functionality, they simply place a weird-looking square symbol at the current caret position. I have tried pasting this symbol in this TextBox but it will not appear.

Upvotes: 1

Views: 84

Answers (1)

AlSki
AlSki

Reputation: 6961

Well you could try this.

  private bool _keyPressHandled;

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        _keyPressHandled = false;

        if (e.Control && e.KeyCode == Keys.Back)
        {
            // since this isn't called very often I'll write it as clearly as possible 

            var leftPart = // Get the section to the left of the cursor
                textBox1.Text.Take(textBox1.SelectionStart)
                    // Turn it around
                    .Reverse()
                    // ignore whitespace
                    .SkipWhile(x => string.IsNullOrWhiteSpace(x.ToString()))
                    // remove one word
                    .SkipWhile(x => !string.IsNullOrWhiteSpace(x.ToString()))
                    // Turn it around again
                    .Reverse()                        
                    .ToArray();
            var rightPart = // what was after the cursor
                    textBox1.Text.Skip(textBox1.SelectionStart + textBox1.SelectionLength);

            textBox1.Text = new string(leftPart.Concat(rightPart).ToArray());
            textBox1.SelectionStart = leftPart.Count();
            textBox1.SelectionLength = 0;

            // Going to ignore the keypress in a second
            _keyPressHandled = true;
        }
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        // See http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keydown.aspx
        if (_keyPressHandled)
        {
            //Prevent an additional char being added
            e.Handled = true;
        }

Upvotes: 1

Related Questions