C# 使文本框中的一组字符表现得像一个字符

C# Make a group of characters in a textbox behave like one character

基本上,我在文本框中有像 sin(cos( 这样的关键字,我希望它们的行为像一个字符。

当我提到下面的整个字符串时,它指的是字符组(例如“sin(”)

sin(为例:

如果插入符号在这个位置(在 s 后面):

如果您按 del,它会删除整个字符串。如果按下右箭头键,插入符号将跳转到 (.

之后

如果插入符在此位置(在 ( 之后):

如果按下 backspace,整个字符串将被删除。如果按下左箭头键,插入符号将跳到 s.

后面

编辑: 感谢 John Skeet 指出了这一点。

选择字符组的任何子字符串(例如 sin( 中的 si)应该 select 整个字符串。

如果难以理解,请见谅,我的想法有点难以表达。

编辑 2: 感谢 Darksheao 为我提供退格键和删除键的答案。我将 delete 段重新定位到 PreviewKeyDown 事件,因为它不适用于 KeyPress 事件。

编辑 3: 使用 charCombinations 做事方式,以下是我如何实现左右键:

#region Right
case Keys.Right:
{
    s = txt.Substring(caretLocation);
    foreach (string combo in charCombinations)
    {
       if (s.StartsWith(combo))
       {
            textBox1.SelectionStart = caretLocation + 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;
                break;
            }
        }
        break;
    }
#endregion

剩下的就是鼠标实现了。任何人?我还意识到用户可能会使用鼠标将插入符号放在其中一个字符串的中间,所以当发生这种情况时,需要将鼠标移到字符串的开头。

这是一段代码,用于设置您希望显示为 "single characters" 的字符组合数组,并设置一个查找它们的处理程序。

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    string[] charCombinations = new string[2];
    charCombinations[0] = "sin(";
    charCombinations[1] = "cos(";
    string txt = this.textBox1.Text;
    int caretLocation = this.textBox1.SelectionStart;
    if (e.KeyCode == Keys.Delete)
    {
        //get text in front
        string s = txt.Substring(caretLocation);
        string notChecking = txt.Substring(0, caretLocation);
        foreach (string combo in charCombinations)
        {
            if (s.StartsWith(combo))
            {
                txt = notChecking + s.Substring(combo.Length - 1);
                break;
            }
        }
    }
    if (e.KeyCode == Keys.Back)
    {
        //get text in behind
        string s = txt.Substring(0, caretLocation);
        string notChecking = txt.Substring(caretLocation);
        foreach (string combo in charCombinations)
        {
            if (s.EndsWith(combo))
            {
                txt = s.Substring(0, s.Length - combo.Length + 1) + notChecking;
                caretLocation -= combo.Length - 1;
                break;
            }
        }
    }
    this.textBox1.Text = txt;
    //changing the txt feild will reset caret location
    this.textBox1.SelectionStart = caretLocation;
}

对此进行一些修改,以便您在 SelectionStart 周围搜索时将处理 Jon 评论中提到的内容。

参考文献:TextBox Event Reference and How do I find the position of a cursor in a text box? C#