I have a richtextbox
on a windows form
the user can enter text into but it needs to be setup so that if the user holds down a key they only get 1 character.
e.g. if they hold down A
then it will only input A and not AAAAAAAAAAAAAAAAAAAAAAAAAAAAA
etc.
From the moment the key is down till the time the key is up I only want that to translate to 1 value.
Any ideas how I can achieve this ?
I guess I need to use KeyDown
and KeyUp
but I'm not sure past that.
You are right about the KeyDown
and KeyUp
events. You can do it this way.
bool keyDown = false;
bool keyPress = false;
private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
{
e.Handled = keyDown;
keyDown = true;
}
private void richTextBox1_KeyUp(object sender, KeyEventArgs e)
{
keyDown = keyPress = false;
}
private void richTextBox1_KeyPress(object sender, KeyPressEventArgs e)
{
e.Handled = keyPress;
keyPress = true;
}
You could subclass TextBox
and override OnKeyDown
and OnKeyUp
methods. If there wasn't any KeyUps
after KeyDown
, just ignore it by setting KeyEventArgs.SuppresKeyPress
to true
. Check the code:
public class MyTextBox:TextBox
{
bool down = false;
protected override void OnKeyDown(KeyEventArgs e)
{
if (!down)
base.OnKeyDown(e);
else
e.SuppressKeyPress = true;
down = true;
}
protected override void OnKeyUp(KeyEventArgs e)
{
base.OnKeyUp(e);
down = false;
}
}
Alternatively you can use KeyUp
and KeyDown
event handlers like this, note that the SuppresKeyPress
is crucial:
bool down = false;
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (down)
e.SuppressKeyPress = true;
down = true;
}
private void textBox1_KeyUp(object sender, KeyEventArgs e)
{
down = false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With