Reputation: 558
I need to determine whether a key, when it is pressed, will change the control's text or not; I need to ignore key presses like Ctrl+Z
or Esc
, but I need to know which key was pressed if the text changed.
Is there any way to know that in the KeyDown
event? Currently, I'm using a flag, set on KeyDown
and checked on TextChanged
, but I was wondering if there is a better way?
Upvotes: 3
Views: 4056
Reputation: 1955
You could catch the KeyPress
event on the text box and if it is a valid key you would set e.handled = false
and if it was a bad key you would set e.handled = true
.
example from: 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;
}
}
Upvotes: 1
Reputation: 73442
You're looking for 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
}
}
Upvotes: 4
Reputation: 10476
There are some keys which produce a Control
char but they also change the text, for example BackSpace
. They have another difficulty: if the textbox
is empty, pressing them (for example BackSpace
) doesn't change the text; so it breaks the previous rule. So Control
characters are not naive to deal with and build a rule upon.
Moreover, consider Ctrl + C
or Shift + Insert
or similar cases. The 'C' key is somehow seductive; it is like pressing 'C
' changes the text but if it was pressed with 'Ctrl'
, it actually didn't change the text. We should check the Modifiers
.
Perhaps you can find other difficulties to deal with and I think the flag
approach is good enough.
Upvotes: 0