Marek
Marek

Reputation: 3575

Collect multiple keypress events

Hello this code down append text to textBox after key is pressed. It writes one line for each key press. May i ask if there is any good solution to collect for example 5 key press and write them in one line?

          private void User_KeyPress(object sender, KeyPressEventArgs e)
    {
        textBox.AppendText(string.Format("You Wrote: - {0}\n", e.KeyChar));
        textBox.ScrollToCaret();
    } 

For example MOUSE wouldn't be written like:

You Wrote: M; You Wrote: O; You Wrote: U; You Wrote: S; You Wrote: E

But the output will be:

You wrote: MOUSE

Upvotes: 0

Views: 677

Answers (3)

poy
poy

Reputation: 10507

You could buffer the key presses until you reach a threshold and then output the entire buffer's contents.

e.g.

Queue<char> _buffer = new Queue<char>();

private void User_KeyPress(object sender, KeyPressEventArgs e)
{
  _buffer.Enqueue(e.KeyChar);

  if(_buffer.Count > 5)
  {
    StringBuilder sb = new StringBuilder("You Wrote: ");
    while(_buffer.Count > 0)
      sb.AppendFormat(" {0}", _buffer.Dequeue());

    Console.WriteLine(sb.ToString());
  }
}

Upvotes: 1

Bit
Bit

Reputation: 1078

Maybe something like:

string testCaptured = string.Empty;
int keyPressed = 0;

private void User_KeyPress(object sender, KeyPressEventArgs e)
{
    if (keyPressed < 5)
    {
        testCaptured += e.keyChar;
        keyPressed++;
    }
    else
    {
        textBox.Text = string.Format("You Wrote: - {0}\n", testCaptured);
        textBox.ScrollToCaret();
    }
} 

Upvotes: 1

Trevor Elliott
Trevor Elliott

Reputation: 11252

Don't call textBox.AppendText. Appending adds to an existing string and combines them.

You want to write something like textBox.Text = String.Format(...)

You should create a private variable in your object to keep track of all the characters and append to that. The class which owns your User_KeyPress method should have a variable like the following:

private string _keysPressed = String.Empty;

Now in your method you can append and output like so:

private void User_KeyPress(object sender, KeyPressEventArgs e)
{
    _keysPressed += e.KeyChar;
    textBox.Text = String.Format("You Wrote: - {0}\n", _keysPressed);
    textBox.ScrollToCaret();
}

Upvotes: 1

Related Questions