0

I'm using a component called QTextBox from Qios DevSuite in my project.

Similar to what happens by default in .NET TextBox, when user presses Control+Backspace on it while typing, instead of deleting the word left from the cursor, character '' is inserted instead.

To resolve this issue, I figured I'd do something like

public class QTextBoxEx : QTextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        if (keyData == (Keys.Control | Keys.Back))
        {
            // here goes my word removal code
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

Is this a good approach or is there already a .NET built in system to implement this kind of behavior? Also, what would be the "cleanest" way of removing the last word from a search string? (I can think of string.Replace and Regex right now)

Joel
  • 7,401
  • 4
  • 52
  • 58

1 Answers1

2
public class QTextBoxEx : QTextBox
{
    protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
    {
        // shortcut to search bar
        if (keyData == (Keys.Control | Keys.Back))
        {
            // 1st scenario: some text is already selected. 
            // In this case, delete only selected text. 
            if (SelectedText != "")
            {
                int selStart = SelectionStart;
                Text = Text.Substring(0, selStart) + 
                    Text.Substring(selStart + SelectedText.Length);

                SelectionStart = selStart;
                return true;
            }

            // 2nd scenario: delete word. 
            // 2 steps - delete "junk" and delete word.

            // a) delete "junk" - non text/number characters until 
            // one letter/number is found
            for (int i = this.SelectionStart - 1; i >= 0; i--)
            {
                if (char.IsLetterOrDigit(Text, i) == false)
                {
                    Text = Text.Remove(i, 1);
                    SelectionStart = i;
                }
                else
                {
                    break;
                }
            }

            // delete word
            for (int i = this.SelectionStart - 1; i >= 0; i--)
            {
                if (char.IsLetterOrDigit(Text, i))
                {
                    Text = Text.Remove(i, 1);
                    SelectionStart = i;
                }
                else
                {
                    break;
                }
            }
            return true;
        }

        return base.ProcessCmdKey(ref msg, keyData);
    }
}

This code assumes two different scenarios:

  • Text already selected: remove selected text only.
  • No selected text: word is deleted.
André Leal
  • 60
  • 1
  • 6