0

您好,此代码一直append texttextBox按下键后。它为每次按键写入一行。请问是否有任何好的解决方案来收集例如 5 个按键并将它们写在一行中?

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

例如 MOUSE 不会写成这样:

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

但输出将是:

You wrote: MOUSE

4

3 回答 3

1

您可以缓冲按键直到达到阈值,然后输出整个缓冲区的内容。

例如

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());
  }
}
于 2013-10-08T19:53:07.917 回答
1

也许是这样的:

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();
    }
} 
于 2013-10-08T19:47:59.707 回答
1

不要打电话textBox.AppendText。追加添加到现有字符串并组合它们。

你想写类似的东西textBox.Text = String.Format(...)

您应该在对象中创建一个私有变量来跟踪所有字符并附加到该变量。拥有您的User_KeyPress方法的类应具有如下变量:

private string _keysPressed = String.Empty;

现在在您的方法中,您可以像这样附加和输出:

private void User_KeyPress(object sender, KeyPressEventArgs e)
{
    _keysPressed += e.KeyChar;
    textBox.Text = String.Format("You Wrote: - {0}\n", _keysPressed);
    textBox.ScrollToCaret();
}
于 2013-10-08T19:41:40.723 回答