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

时间:2015-05-12 14:04:56

标签: c# string textbox

基本上,我在文本框中有sin(cos(等关键字,我希望它们的行为类似于单个字符。

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

sin(为例:

如果插入符号处于此位置(s后面):

enter image description here

如果按下del,则会删除整个字符串。如果按下右箭头键,则插入符号将跳至(

之后

如果插入符号处于此位置((之后):

enter image description here

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

后面

修改 感谢John Skeet指出了这一点。

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

对不起,如果难以理解,我想到的是有点难以理解。

编辑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

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

1 个答案:

答案 0 :(得分:2)

Here is a section of code that sets up an array of the character combinations that you want to be seen as "single characters" and sets up a handler that looks for them.

SELECT COALESCE(a.ColumnA,b.ColumnA) AS ColumnA
      ,COALESCE(a.ColumnB,b.ColumnB) AS ColumnB
      ,a.ColumnC
      ,b.ColumnD
FROM Table1 a
FULL JOIN Table2 b
  ON a.ColumnA = b.ColumnA
  AND a.ColumnB = b.ColumnB

Making some modifications to this so that you are searching around the SelectionStart will handle what was mentioned in Jon's comment.

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