基本上,我有喜欢的关键词sin(
和cos(
一个文本框,我想有更像一个单个字符.
当我提到下面的整个字符串时,它指的是字符组(例如" sin(
")
以sin(
身份为例:
如果插入符号处于此位置(后面s
):
如果按下del
,则会删除整个字符串.如果按下右箭头键,插入符将跳转到(
.
如果插入符号处于此位置(之后(
):
如果backspace
按下,则将删除整个字符串.如果按下左箭头键,插入符将跳到后面s
.
编辑: 感谢John Skeet指出这一点.
选择字符组的任何子字符串(例如si
from 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
Run Code Online (Sandbox Code Playgroud)
剩下的就是鼠标实现.任何人?我还意识到用户可以使用鼠标将插入符号放在其中一个字符串的中间,因此当发生这种情况时,需要将鼠标移动到字符串的开头.
小智 2
下面是一段代码,用于设置您希望被视为“单个字符”的字符组合数组,并设置一个查找它们的处理程序。
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;
}
Run Code Online (Sandbox Code Playgroud)
对此进行一些修改,以便您在 SelectionStart 周围搜索将处理 Jon 的评论中提到的内容。
参考:TextBox 事件参考和如何查找文本框中光标的位置?C#
归档时间: |
|
查看次数: |
304 次 |
最近记录: |