我需要确定按下按键时是否会改变控件的文本;我需要忽略像Ctrl+Z
或Esc
这样的按键操作,但是如果文本发生了变化,我需要知道按下了哪个键。
有没有办法知道 KeyDown
事件?目前,我正在使用一个标记,设置在KeyDown
并在TextChanged
上进行检查,但我想知道是否有更好的方法?
答案 0 :(得分:4)
您正在寻找Char.IsControl
private Keys lastKey = Keys.None;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
lastKey = e.KeyData;
}
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
if (Char.IsControl(e.KeyChar))
{
e.Handled = true;//prevent this key press
Keys pressedKey = this.lastKey;
//Do your stuff with pressedKey here
}
}
答案 1 :(得分:1)
您可以在文本框中捕获KeyPress
事件,如果它是有效密钥,您可以设置e.handled = false
,如果它是错误的密钥,您可以设置e.handled = true
。
示例来自:here
private void keypressed(Object o, KeyPressEventArgs e)
{
// The keypressed method uses the KeyChar property to check
// whether the ENTER key is pressed.
// If the ENTER key is pressed, the Handled property is set to true,
// to indicate the event is handled.
if (e.KeyChar == (char)Keys.Return)
{
e.Handled = true;
}
}
答案 2 :(得分:0)
有些密钥会生成Control
个字符,但它们也会更改文本,例如BackSpace
。他们还有另一个困难:如果textbox
为空,按下它们(例如BackSpace
)不会改变文本;所以它打破了以前的规则。所以Control
字符对于处理和建立规则并不幼稚。
此外,请考虑Ctrl + C
或Shift + Insert
或类似情况。 'C'键在某种程度上是诱人的;就像按“C
”更改文本一样,如果用'Ctrl'
按下它,实际上并没有改变文本。我们应该检查Modifiers
。
也许您可以找到其他困难来处理,我认为flag
方法已经足够了。