我正在开发一个简单的文本编辑器,我在自己添加一些字符时遇到了麻烦......我做了以下示例代码,我正在做什么...当我输入字符时,它不会在当前光标位置添加相应的字符....
另一个疑问是,如何让程序忽略我再次输入时添加的字符...... ??
Dictionary<char, char> glbin = new Dictionary<char, char>
{
{'(', ')'},
{'{', '}'},
{'[', ']'},
{'<', '>'}
};
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int line = textBox1.GetLineFromCharIndex(textBox1.SelectionStart);
int column = textBox1.SelectionStart - textBox1.GetFirstCharIndexFromLine(line);
if(glbin.ContainsKey(e.KeyChar))
textBox1.Text.Insert(column, glbin[e.KeyChar].ToString());
}
答案 0 :(得分:4)
String是不可变对象,Text属性上的Insert调用生成string的新实例,该实例未在任何地方分配。
要忽略char,您需要将KeyPressEventArgs Handled属性设置为true(您可能需要关闭字符的逆字典)。
您需要将代码更改为:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
int index = textBox1.SelectionStart;
if(glbin.ContainsKey(e.KeyChar))
{
var txt = textBox1.Text; // insert both chars at once
textBox1.Text = txt.Insert(index, e.KeyChar + glbin[e.KeyChar].ToString());
textBox1.Select(index + 1, 0);// position cursor inside brackets
e.Handled = true;
}
else if (glbin.Values.Contains(e.KeyChar))
{
// move cursor forward ignoring typed char
textBox1.SelectionStart = textBox1.SelectionStart + 1;
e.Handled = true;
}
}