0

通常のWinFormsC#テキストボックスコントロールのデフォルトの動作を変更して、を押すと1文字だけでなく単語全体backspaceが削除されるようにしたいと思います。

理想的には、この特別な動作は、キャレットの位置が空白文字の前にある場合にのみ実行したいと思います。例えば; backspaceカレットが「helloworld|」にあるときに1回押す それでも1文字だけ削除する必要があり、結果として「helloworl|」になります。-ただし、caretが「helloworld|」にある場合 を押すbackspaceと、結果は「hello|」になります。

4

4 に答える 4

2

まず、あなたのイベントのためKeyEventHandlerに追加する必要がありますKeyDownTextBox

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

ほら、私はそれをテストしましたが、うまくいきます:

    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 に答える
1

keypress/keydown イベントを見てください。

于 2012-10-25T20:51:20.727 に答える
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 に答える