基本上,我在文本框中有像 sin(
和 cos(
这样的关键字,我希望它们表现得像一个字符。
当我在下面提到整个字符串时,它指的是字符组(例如“sin(
”)
以sin(
为例:
如果插入符号在这个位置(在 s
后面):
如果您按下 del
,它会删除整个字符串。如果按下右箭头键,插入符将跳转到 (
之后。
如果插入符号在这个位置(在 (
)之后):
如果按下 backspace
,整个字符串将被删除。如果按下左箭头键,插入符号将跳到 s
后面。
编辑: 感谢 John Skeet 指出了这一点。
选择字符组的任何子字符串(例如 sin(
) 中的 si
应该选择整个字符串。
抱歉,如果难以理解,我的想法有点难以表达。
编辑 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
剩下的就是鼠标实现了。任何人?我还意识到用户可能会使用鼠标将插入符放在其中一个字符串的中间,因此当发生这种情况时,需要将鼠标移至字符串的开头。
最佳答案
下面是一段代码,用于设置您希望被视为“单个字符”的字符组合数组,并设置一个查找它们的处理程序。
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和 How do I find the position of a cursor in a text box? C#
关于C# 使文本框中的一组字符表现得像一个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30193302/