In a key pressed event I am using the code here to disable some keys (e.g. I want to allow typing only numbers). However, this also disable shortcuts like CTRL-C and so on. I can still copy and paste with the mouse, and I can still use those shorcuts in which I do not use my KeyPressEventHandler
.
Here is the code I am using:
class IntegerTextBox : TextBox
{
public IntegerTextBox()
{
KeyPress += new KeyPressEventHandler(accept_only_digits); //disable "wrong" key presses, https://stackoverflow.com/a/4285768/2436175
}
void accept_only_digits(object sender, KeyPressEventArgs e)
{
char ch = e.KeyChar;
if (!char.IsNumber(ch) && ch != (char)Keys.Back && ch != (char)Keys.ControlKey) //The latter doesn't help
{
e.Handled = true;
return;
}
}
}
However, the KeyPressEventArgs, differently from the KeyEventArgs, doesn't seem to have the information necessary to know if the ctrl key is pressed. Is there a way to circumvent this? For example something to prevent my KeyPressEventHandler
to be called if the ctrl key is currently pressed?
Note 1: I am aware that in this way users will be allowed to paste also garbage
Note 2: I have also code to handle inserting negative numbers, but it's not relevant at this stage