C# TextBox 覆盖方向键选择函数

标签 c# textbox

基本上,从这个 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
    }
}

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

enter image description here

第二个问题在于左键,左键选择不会选择整个字符:

enter image description here

对于这种情况,应选择整个单词 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;

因为我使用 += 而不是 =

关于C# TextBox 覆盖方向键选择函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30363561/

相关文章:

c# - 我应该如何正确连接两个表,以便我可以访问其中一个实体中的属性?

javascript - 多个文本字段似乎无法使用单选按钮启用它们

c# - 当文本框失焦时显示文本框文本突出显示

ios - 将输入数字存储在文本框中的变量中

c# - 获取委托(delegate)的 IntPtr 并调用

c# - Log4net 生成错误的日志文件名

C# 使用 RSA DER 格式公钥解密文件

c# - 从非静态类访问静态方法可能在 java 而不是在 c# 中

基于文本框输入的JavascriptremoveEventListener

c# - .NET 4.5 的奇怪文本框问题 - 不允许 '.'