我想修改常规WinForms C#文本框控件的默认行为,以便按 backspace 删除整个单词,而不只删除单个字符。
理想情况下,当插入位置位于空格字符的前面时,我希望此特殊行为仅。例如;当插入符号位于“hello world |”时,按 backspace 一次应该仍然只删除一个字符,导致“hello worl |” - 但如果插入符号位于“hello world |”当我按 backspace 时,结果应为“hello |”
答案 0 :(得分:2)
首先,您需要为KeyEventHandler
KeyDown
事件添加TextBox
this.textBox1.KeyDown += new System.Windows.Forms.KeyEventHandler(this.textBox1_KeyDown);
之后,您可以像这样处理事件:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
TextBox t = (TextBox)sender;
if (e.KeyCode == Keys.Back)
{
int carretIndex = t.SelectionStart;
if (carretIndex>0 && carretIndex == t.Text.Length && t.Text[carretIndex-1] == ' ')
{
int lastWordIndex = t.Text.Substring(0, t.Text.Length - 1).LastIndexOf(' ');
if (lastWordIndex >= 0)
{
t.Text = t.Text.Remove(lastWordIndex + 1);
t.Select(t.Text.Length, 0);
}
else
{
t.Text = string.Empty;
}
}
}
}
答案 1 :(得分:1)
看一下keypress / keydown事件。
答案 2 :(得分:1)
在这里,我测试了它并且工作正常:
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
String[] chars = new String[1]{" "};
if(e.KeyValue == 8)
{
var temp = (from string s in textBox1.Text.Split(chars, StringSplitOptions.None)
select s).ToArray();
temp[temp.Length-1] = "";
textBox1.Text = String.Join(" ",temp).ToString();
SendKeys.Send("{END}");
}
}
答案 3 :(得分:0)
它是一个伪代码,我希望你会发现它有用:
// check backspace is pressed
if keycode==keycode(backspace) then
// testing cursor is just after space(113) character
if string[string length] == keycode(space) then
// loop through string in reverse order
loop each character in reverse
// start removing each character
remove the characters
till find 2nd space
end if
end if