【问题标题】:C# TextBox Override Arrow Key Select FunctionC# TextBox 覆盖箭头键选择函数
【发布时间】:2015-05-21 02:29:27
【问题描述】:

基本上,从question 继续,当用户按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"};

【问题讨论】:

    标签: c# textbox


    【解决方案1】:

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

    我在这个模型中修复了你的代码:

            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;

    因为我使用+= 而不是=

    【讨论】:

      猜你喜欢
      • 2013-06-11
      • 1970-01-01
      • 2019-08-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多