C# TextBox 覆盖箭头键 Select 函数

C# TextBox Override Arrow Key Select Function

基本上,从这个 继续,当用户按下 shift + 向左或向右时,我需要它 select 整个字符组。

我目前的代码(在 PreviewKeyDown 事件下):

string s;
int caretLocation = textBox1.SelectionStart;
string txt = textBox1.Text;
if (e.Shift) 
{
    switch (e.KeyCode)
    {
        #region Right
        case Keys.Right:
            {
                s = txt.Substring(caretLocation);
                foreach (string combo in charCombinations)
                {
                    if (s.StartsWith(combo))
                    {
                        textBox1.SelectionLength = combo.Length - 1;
                        break;
                    }
                }
                break;
            } 
        #endregion
        #region Left
        case Keys.Left:
            {
                s = txt.Substring(0, caretLocation);
                foreach (string combo in charCombinations)
                {
                    if (s.EndsWith(combo))
                    {
                        textBox1.SelectionStart = caretLocation - combo.Length + 1;
                        textBox1.SelectionLength = combo.Length + 1
                        break;
                    }
                }
                break;
            }
        #endregion
    }
}

第一个问题出在右键上,如果连续有两个这样的字符组,插入符号不会从下图的位置进一步向右移动:

第二个问题在于左键,其中左键 selection 只是 select 整个字符:

对于这种情况,整个单词 sin( 应该 selected。

提前致谢!

charCombinations 定义为:

    private static readonly string[] charCombinations = new string[] { "asinh(", "acosh", "atanh(",
        "sinh(", "cosh(", "tanh(", "asin(", "acos(", "atan(", "sin(", "cos(", "tan(", 
        "log(", "ln(", "PI", "e", "Phi"};

您必须将下一个文本长度添加到上一个长度。

我修复了你这个型号的代码:

        case Keys.Right:
        {
            s = txt.Substring(caretLocation);

            foreach (string combo in charCombinations)
            {
                if (s.StartsWith(combo))
                {
                    textBox1.SelectionLength += combo.Length - 1;
                    break;
                }
            }
            break;
        }

重要的一行是:textBox1.SelectionLength += combo.Length - 1;

因为我使用 += 而不是 =