TextBox控件之间是否存在这种不一致的行为

时间:2013-07-05 10:06:31

标签: .net wpf windows winforms io

我刚做了一个简单的笔记应用程序,我注意到很多次Windows窗体应用程序中的TextBox控件不支持 Tab 的退格。但是我注意到了#34; TextBox"网站中的控件(大部分都是)以及WPF应用程序中的TextBox控件也支持 Tab 的退格。

如果你不确定我的意思,请输入用空格分隔的几个单词,然后按住 Ctrl 键并点击 Backspace 键。您会注意到它不是一个退格,而是一个完整的Tab空间。

为什么这种行为如此不一致?

是否因为只有较新版本的Text输入控件支持此行为?它与我的键盘设置有关吗?

问题:我应该如何在我的Windows窗体应用程序TextBox Control中最好地实现/强制使用Back-Tab-space,同时也尊重用户的Windows标签间距设置(即,按键时Tab键会产生的空格数)?

注意:在不支持此功能的控件中,它们只是在当前插入位置放置一个看起来很奇怪的方形符号。我已尝试在此TextBox中粘贴此符号,但它不会出现。

1 个答案:

答案 0 :(得分:1)

嗯,你可以试试这个。

  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;
        }