繁体   English   中英

C#TextBox覆盖箭头键选择功能

[英]C# TextBox Override Arrow Key Select Function

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

我拥有的当前代码(在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
    }
}

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

在此处输入图片说明

第二个问题与左键有关,其中左键选择只是不能选择整个字符:

在此处输入图片说明

对于这种情况,应选择整个单词sin(

提前致谢!

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;

因为我用+=代替=

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM