Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow only 1 value per key press

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.

like image 315
user476683 Avatar asked Mar 08 '13 09:03

user476683


2 Answers

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;
}
like image 152
VladL Avatar answered Nov 03 '22 00:11

VladL


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;
}
like image 22
Nikola Davidovic Avatar answered Nov 02 '22 23:11

Nikola Davidovic