0

我想修改常规 WinForms C# 文本框控件的默认行为,以便按下backspace删除整个单词而不是单个字符。

理想情况下,我希望当插入符号位置位于空白字符前面时才具有这种特殊行为。例如; 当插入符号位于“hello world|”时按backspace一次 仍然应该只删除一个导致“hello worl|”的字符 - 但如果插入符号位于“hello world |” 当我按 时backspace,结果应该是“你好 |”

4

4 回答 4

2

首先,您需要为您KeyEventHandlerKeyDown事件添加TextBox

this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);

之后,您可以像这样处理事件:

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox t = (TextBox)sender;
            if (e.KeyCode == Keys.Back)
            {
                int carretIndex = t.SelectionStart;
                if (carretIndex>0 && carretIndex == t.Text.Length && t.Text[carretIndex-1] == ' ')
                {
                    int lastWordIndex = t.Text.Substring(0, t.Text.Length - 1).LastIndexOf(' ');
                    if (lastWordIndex >= 0)
                    {
                        t.Text = t.Text.Remove(lastWordIndex + 1);
                        t.Select(t.Text.Length, 0);
                    }
                    else
                    {
                        t.Text = string.Empty;
                    }
                }
            }
        }
于 2012-10-25T21:14:34.170 回答
1

看看 keypress/keydown 事件。

于 2012-10-25T20:51:20.727 回答
1

给你,我测试了它,它工作正常:

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        String[] chars = new String[1]{" "};

        if(e.KeyValue == 8)
        {
            var temp = (from string s in textBox1.Text.Split(chars, StringSplitOptions.None)
                             select s).ToArray();

            temp[temp.Length-1] = "";


            textBox1.Text = String.Join(" ",temp).ToString();
            SendKeys.Send("{END}");
        }

    }
于 2012-10-25T21:25:12.243 回答
0

它是一个伪代码,希望对您有所帮助:

// check backspace is pressed
if keycode==keycode(backspace) then
    // testing cursor is just after space(113) character
    if string[string length] == keycode(space) then
    // loop through string in reverse order
    loop each character in reverse
        // start removing each character 
        remove the characters
    till find 2nd space

    end if
end if
于 2012-10-25T21:01:44.467 回答